This post is part of a Node.js series and is a continuation of my last post, Setting up a Node.js Project with NPM.
Let’s start writing our server. We will be using the Express server framework to write our server so the first thing we need to do is install Express.
Installing Express
Make sure you have a command prompt open at the root of your project directory. To install Express as a dependecy of your project, run npm install express --save
.
Let’s break down this command so we understand all of it's parts. We are using the npm install
command followed by the name of the package we want to install, express
, followed by the --save
flag which means “save a reference to this dependency in our package.json file”.
After you run this command, take a look inside your project folder. You should see a new folder called node_modules
. You might also see a new file called package-json.lock
. (This file is a fairly new addition in Node. I’ve only recently started seeing it in the latest versions of Node.js. We don’t need to worry too much about it. It’s mostly responsible for keeping track of our dependency tree.)
If you open up the node_modules
folder, you’ll see a ton of other folders in addition to an express
folder. These other folders are dependencies required by Express. We should never need to do anything with anything inside the node_modules
folder. It’s something you can ignore for the most part. In fact, this is a folder you will definitely want to add to your .gitignore
file if you are tracking this project with Git!
Now let’s look at our package.json file again. You should see a new object added called “dependencies”. Inside this object you should see "express", along with the version we just installed.
"dependencies": {
"express": "^4.16.2"
}
This “dependencies” section of our package.json
file is super important. It keeps a reference to all of the dependencies of our project. Remember, the reason we are seeing this new section is because of the --save
flag at the end of the npm install express --save
command we ran. Without --save
Express would still be downloaded to the node_modules
folder, but there would be no reference to it in our package.json
file.
Installing Dependencies using package.json
Let’s put this “dependencies” section of our package.json
file to the test. Go ahead and delete the node_modules
folder in your project directory. Go ahead. Don’t be scared. :)
Now, in your command prompt run npm install
. Afterward, check your project folder again. The node_modules
folder should be back! Hooray! That’s because npm install
will install all dependencies listed in our package.json
file. That is why we can ignore this folder in our Git repository. This also means that whenever you clone a Node project to your computer, one of the first commands you will run is npm install
so you can get all of the missing dependencies.
Writing our Express Server
Note: In this tutorial we are going to write JavaScript using the ECMAScript 5 standard (ES5) rather than the newer and more popular ES6. We are using the latest version of Node so we could easily use ES6 or even ES7 JavaScript, but if you haven’t setup your IDE or text editor to interpret the latest JavaScript standard then you will see lots of errors and poor syntax highlighting. I don’t want to trip you up with IDE configuration in this tutorial, so I am going to stick with the basics. Feel free to use ES6 or ES7 in place of the ES5 JavaScript I’ll be using in this tutorial if you want. It really isn’t going to differ that much.
Open up your index.js
file. The first thing we need to do is require Express and create a reference to it. To do that we are going to add this line of code:
var express = require('express');
This line of code requires the express
module and assigns it to a variable named express
so that we can reference it further down in our file. Since express
is a module that we installed using npm, it lives in our node_modules
folder, which means we don’t need to specify a path to the dependency. When a module name is provide with no path, Node’s require()
function checks the node_modules
folder for the dependency by default.
Next, we need to create an Express application and make a reference to it. To do that we need to add this line of code:
var app = express();
In this line, we are calling express()
which creates an Express application. Then, we are assigning it to a variable named app
. We will be referencing app
a lot in our project.
Now let’s write the last bit of code we need before we can test this thing out. We need Express to start up an HTTP server and listen for connections to a port, which we will define. To do that we will use app.listen()
to which we will pass two parameters. First, we will give it the port number, then we will give it a “callback function” that Express will call once the server starts listening to the given port (Check out the Express docs for more info on app.listen). All of this might sound a little crazy right now, but it should make a little more sense once we test it out. Let’s add this code to the end of our index.js file.
app.listen(3000, function(){
console.log("Listening on port 3000!")
});
This code might look a little scary, but it's really pretty simple, so let’s break it down.
First, we’ve got app.listen();
and inside of its parentheses we have two parameters separated by a comma. The first parameter is the port number we want our server to listen to, 3000
. The second parameter is a function expression that logs the message "Listening on port 3000!"
.
That’s it! That is the simplest server you can write with Node and Express. When you are done, your index.js
file should look like this:
var express = require('express');
var app = express();
app.listen(3000, function(){
console.log("Listening on port 3000!")
});
Running our Simplest Server
Now that we have written the code for our server, let’s run it! To do that we need to go over to our command prompt and run node index
. We are using the node command to execute our index.js
file. We reference the file as index
without the .js
file extension.
If all goes well you should see the response “Listening on port 3000!” in your command prompt. That means the server is running!
The server you just created, that is now running, didn’t just log the message and end execution. This server will continue to run until we stop it, or until a server error causes it to crash. We haven't written enough code for this server to crash so let’s go ahead and stop it. To stop the server from running, press the CTRL
and C
keys on your keyboard at the same time.
Ok, maybe that wasn’t the most exciting thing you’ve ever done but you've just learned a whole lot of fundamental Node.js server magic. Great job!
In the next post we will actually serve up some content that will show in the browser when we visit specified urls.