Modules in Javascript

Differences between Node.js and browsers


Modules in Javascript

Differences between Node.js and browsers

There are many differences between Node.js and browser environments, but many of them are small and inconsequential in practice. For example, in our Asynchronous lesson, we noted how Node’s setTimeout has a slightly different return value from a browser’s setTimeout. Let’s go over a few notable differences between the two environments.

Global vs Window

In the Node.js runtime, the global object is the object where global variables are stored. In browsers, the window object is where global variables are stored. The window also includes properties and methods that deal with drawing things on the screen like images, links, and buttons. Node doesn’t need to draw anything, and so it does not come with such properties. This means that you can’t reference window in Node.

Most browsers allow you to reference global but it is really the same object as window.

Document

Browsers have access to a document object that contains the HTML of a page that will be rendered to the browser window. There is no document in Node.

Location

Browsers have access to a location that contains information about the web address being visited in the browser. There is no location in Node, since it is not on the web.

Require and module.exports

Node has a predefined require function that we can use to import installed modules like readline. We can also import and export across our own files using require and module.exports. For example, say we had two different files, animals.js and cat.js, that existed in the same directory:

If we execute animals.js in Node, the program would print ‘Sennacy is a great pet!’.

Browsers don’t have a notion of a file system so we cannot use require or module.exports in the same way.

The fs module

Node comes with an fs module that contains methods that allow us to interact with our computer’s File System through JavaScript. No additional installations are required; to access this module we can simply require it. We recommend that you code along with this reading. Let's begin with a change-some-files.js script that imports the module:

// change-some-files.js