Every application has to be set up, so we'll begin with that. Create a folder for your project—I'll call mine simpleBlog
—and inside that, create a file named package.json
. If you've used Node.js before, you know that the package.json
file describes the project; lists the project home page, repository, and other links; and (most importantly for us) outlines the dependencies for the application.
Here's what the package.json
file looks like:
{ "name": "simple-blog", "description": "This is a simple blog.", "version": "0.1.0", "scripts": { "start": "nodemon server.js" }, "dependencies": { "express": "3.x.x", "ejs" : "~0.8.4", "bourne" : "0.3" }, "devDependencies": { "nodemon": "latest" } }
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
This is a pretty bare-bones package.json
file, but it has all the important bits. The name
, description
, and version
properties should be self-explanatory. The dependencies
object lists all the npm packages that this project needs to run: the key is the name of the package and the value is the version. Since we're building an ExpressJS backend, we'll need the express
package. The ejs
package is for our server-side templates and bourne
is our database (more on this one later).
The devDependencies
property is similar to the dependencies
property, except that these packages are only required for someone working on the project. They aren't required to just use the project. For example, a build tool and its components, such as Grunt, would be development dependencies. We want to use a package called nodemon
. This package is really handy when building a Node.js backend: we can have a command line that runs the nodemon server.js
command in the background while we edit server.js
in our editor. The nodemon
package will restart the server whenever we save changes to the file. The only problem with this is that we can't actually run the nodemon server.js
command on the command line, because we're going to install nodemon
as a local package and not a global process. This is where the scripts
property in our package.json
file comes in: we can write simple script, almost like a command-line alias, to start nodemon
for us. As you can see, we're creating a script called start
, and it runs nodemon server.js
. On the command line, we can run npm start
; npm knows where to find the nodemon
binary and can start it for us.
So, now that we have a package.json
file, we can install the dependencies we've just listed. On the command line, change to the current directory to the project directory, and run the following command:
npm install
You'll see that all the necessary packages will be installed. Now we're ready to begin writing the code.