Node.js for Rails developers, Part 2 (Node and Express)

This post is part of a series for Rails developers who want to get started with Node.js.
After discussing technology options, we’re ready to get started with the essential technologies - Node and Express.
The goal of this post is to generate a new application and view it in a local web browser.

Don’t worry if you’re unfamiliar with the location and purpose of each of these files. Throughout this series, we will modify our application’s directory structure and file names to resemble Rails conventions, and the similarities between Express and Rails will be become more clear.

Installing Dependencies

The role of the package.json file is to declare package dependencies. Rubyists can think of it like a Gemfile.

cd robots_app
npm install

This command installs all NPM module dependencies declared in package.json. It creates a new directory called node_modules/, which contains source code for all locally-installed modules. Before committing our project to version control, we’ll want to ignore all files in this directory.

touch .gitignore

Update .gitignore according to the following template:

# .gitignore
node_modules/

Running a Local Web Server

Run the development web server.

DEBUG=robots_app:* npm start

You should now be able to visit the application’s home page in your browser at localhost:3000.

After demonstrating the ability to view the application locally in a browser, stop the web server by typing ctrl-c.

Upgrading Local Web Server

One shortcoming of the default web server is that it requires us to restart the server each time we make a change to one of our application’s files. During development, this happens a lot, so we’ll want to upgrade our development web server. We can use a module called Nodemon, which will automatically detect file changes and obviate our need to take manual action.