Kickstart your first Node and Express.js 4 app

I recently spent some time getting up to speed with Express 4 for Node, and thought I would write up a few notes for anyone new to Node or Express 4. In this post I'll use the Express 4 generator to build the scaffolding to our app, and I'll go over a few tips about starting app.

With Node installed, we generate a new app with the following command:

$ express myapp

after everything installs properly, you’re instructed to run the following command:

$ DEBUG=myapp ./bin/www

So what the heck is going on here? If you’ve worked with Express 3 apps you’d be used to running something like “node myapp.js”. What’s with all this new business then? After a bit of digging in the Express website (http://expressjs.com/migrating-4.html), I came across this:

If you peek at the npm start script in package.json file, you will notice that the actual command that starts the app is node ./bin/www, which used to be node app.js in Express 3. Since the app.js file generated by the Express 4 generator is now a Node module, it can no longer be started independently as an app (unless you modify the code). It has to be to be loaded in a Node file and started via the Node file. The Node file is ./bin/www in this case.

After some more googling I came across this stackoverflow post that said:

The bin\ directory serve as a location where you can define your various startup scripts, the www is an example on how it should looks like, ultimately you could have startup script like test, stop or restart etc. Having this structure allows you to have different configurations without touching the app.js.

So there you have it, all is good. If you'd like, you can ignore the Express instructions and just run "npm start".

But what if you’re working with something like nodemon? What do you do? Easy enough, just pop open the package.json file, and change your startup scripts from this:

"scripts": {
"start": "node ./bin/www"
},

to this

"scripts": {
"start": "nodemon ./bin/www"
},

Now you can just run "npm start" and nodemon will be called for you.

Questions, comments, improvements?