×
By the end of this chapter, you should be able to:
nvm
to manage different versions of Node.module.exports
and require
to manage different JS files in a Node app.Up until now, we have been writing JavaScript exclusively in the browser, but the browser isn't the only JavaScript environment. Today, we can use JavaScript to build desktop applications, mobile applications, and server-side applications. The technology that enables us to build these types of applications in JavaScript is Node.js.
Easy way - You can download and install node.js here for OSX, Windows, and Linux.
Advanced way (recommended) - There is a tool called nvm which stands for "Node Version Manager" which is a great way to maintain different versions of Node on your machine. Here is the link to nvm installation instructions. All you have to do is copy and paste one of the install scripts into your terminal and then copy and paste the export
statement to add it to your PATH.
If you've got nvm installed, you can do nvm install node
to install the latest version of node or nvm install node
to install the latest version of node and then run nvm alias default node
to ensure that you always use that version.
Other essential nvm commands:
- nvm current
displays the current version of Node in use
- nvm ls
see all the installed versions of Node on your machine
- nvm use 9.0.0
tell nvm to use a specific version of Node
- nvm alias default 9.0.0
set the default version of Node
Once Node is installed, simply type node
from the terminal to enter the node REPL, which is a command-line interface for JavaScript. Your terminal becomes a Node environment, and you can type the following:
console.log("Hello World!");
to have it immediately printed out.
Type .exit
to get out of the node REPL.
We can also execute JavaScript files with Node.
From your command line, create a file called first.js
and add the following text:
console.log("Hello World!");
To run this file, simply type node first.js
(assuming you're still in the same directory). We should see "Hello World!" appear in our terminal! (If you are not comfortable using the terminal, make sure you go through our free Terminal and Unix course first.)
Get up and running with Node.js via the following screencast:
Node.js comes with built-in support for modules. These are not the same as ES2015 modules; these are called Common.js modules and have a syntax that makes use of the require
, module
, and exports
keywords. In Common.js, every JavaScript file is a module. Since we are not using <script>
tags (as we are not in the browser), we need a way of loading JavaScript from one file to another, and modules are our answer.
Let's take a look at some examples using Node.js modules. Create a file called helpers.js
, which will export some data to another file called main.js
. In our helpers.js
, let's add the following:
module.exports = { name: "Elie", sayHi() { console.log(`Hi ${this.name}!`); } };
Now in our main.js
, let's add the following:
const helpers = require("./helpers");
helpers.sayHi();
If we run node main.js
we should see the text "Hi Elie!" in the console. So how have we done this? We used the module.exports
object to send an object from one file (helpers.js
) to another (main.js
).
To import the module we use the require
keyword followed by the name of a module. Notice that no .js
is needed to reference the file because it is assumed to be a .js
file by default.
Also notice that we are using a relative path here (i.e. we have to include ./
). This is very important, because if we do not use a relative path, Node will assume you're referencing a built-in module or a package. When you are using your own modules, always use relative paths.
Let's make a file called moreHelpers.js
and let's use the exports
syntax.
exports.sayHello = function() { console.log("Hello!"); }; exports.sayGoodbye = function() { console.log("Goodbye!"); }; exports.firstName = "Elie";
We can see above that instead of wrapping everything inside of the module.exports
object, we can attach values to the exports
object, which is basically shorthand for module.exports
. Let's require
this module back in our main.js
const helpers = require("./helpers"); const moreHelpers = require("./moreHelpers"); helpers.sayHi(); console.log(moreHelpers.firstName); moreHelpers.sayHello(); moreHelpers.sayGoodbye();
Let's create a new file called evenMoreHelpers.js
module.exports = function() { console.log("I am the entire module!"); };
Here we are overriding module.exports to point to a function instead of an object, so when we require this module, it gets imported as a function!
const helpers = require("./helpers"); const moreHelpers = require("./moreHelpers"); const evenMoreHelpers = require("./evenMoreHelpers"); helpers.sayHi(); console.log(moreHelpers.firstName); moreHelpers.sayHello(); moreHelpers.sayGoodbye(); evenMoreHelpers(); // this is a function on its own!
Since Common.js modules are plain objects most of the time, they of course also support object-notation shorthand and ES6 destructuring, like so:
pets.js
const myPets = { dog: "Whiskey", cat: "Moxie" }; module.exports = { myPets };
otherFile.js
const { myPets } = require("../pets"); const { cat, dog } = myPets; console.log(cat); // Moxie console.log(dog); // Whiskey
A nice benefit to using Common.js files is utilizing index files. In any folder, you may have a file named index.js
, which lets you reference its parent folder instead of the actual file itself. In other words, these two syntaxes are equivalent:
var models = require("./models/index"); // /index is not necessary in a folder var models = require("./models");
When building larger apps, you can leverage this advantage by having your index.js
files require
everything in their folder and then export a big object to the main file.
Say, for example, we have a models
folder with three files in it:
models/ first.js second.js third.js
We can create an index file that just exports those three for convenient imports everywhere else:
models/index.js
exports.first = require("./first"); exports.second = require("./second"); exports.third = require("./third");
Then in our main.js
file, we can import everything easily:
main.js
const { first, second, third } = require("./models");
Which makes large application code pretty clean!
If you're wondering why Node.js doesn't support ES6 module syntax such as import
, export default
, etc., well, they're working on it! It's a complicated topic, but if you are interested, you can read more here.
Get up and running with Node.js via the following screencast:
When you're ready, move on to Core Node.js Modules