Some Best Practices for Starting Your Node.js Project
Node.js is one of the most popular platforms. Whilst it is easy to get started on Node.js projects, once you get beyond the basic applications, knowing how to best structure your code and how to deal with errors can become tricky.
Here are some best practices that can help keeping your Node.js project on track.
Start projects with npm init
Creating a new project using npm init
will create a new package.json
which allows you to add metadata to help others working on the project that have the same setup as you.
$ mkdir my-project
$ cd my-project
$ npm init
Setup .npmrc
The - -save
flag updates the package.json
with the dependency. When other developers clone the project, they know they have the right dependencies thanks to this flag.
NPM also adds a leading caret ^
to all versions. Consequently, when someone runs npm install
, they may get different versions of the modules than what you have. While updating modules is always a good practice, having a team of developers all running against slightly different versions of dependencies can lead to differences in behaviour or availability of APIs.
You should therefore make sure everyone is on the same version. To make this easier, the .npmrc
file has some useful properties that can make sure npm install
always updates the package.json
and enforces the version of installed dependency to be an exact match.
Run the following lines in your terminal:
$ npm config set save=true
$ npm config set save-exact=true
Now when you run npm install
, you can be sure the dependency is saved and will be locked down to the version you installed.
Add scripts to your package.json
All applications need a launch script. NPM has a standard way to start all node applications.
Add a scripts
property and object to your package.json
with a start
key. It’s value should be the command to launch your app. For example:
"scripts": {
"start": "node myapp.js"
}
As soon as someone runs npm start
, NPM will run node myapp.js
with all the dependencies from node_modules/.bin
on your $PATH
. This means you can avoid having to do global installs of NPM modules.
Some more script hooks worth knowing are postinstall and test:
"scripts": {
"postinstall": "bower install && grunt build",
"start": "node myapp.js",
"test": "node ./node_modules/jasmine/bin/jasmine.js"
}
The postinstall
script is run after npm install
is run. There’s also preinstall
if you need to run something before all the NPM dependencies are installed.
The test
script is run when someone runs npm test
. The tests can be run without figuring out which test framework is used etc.
You can also add your own custom scripts. They can then be run using npm run-script {name}
— and you can give the team a central set of launch scripts.
More tips in my next blog next week.
Susanne Lundkvist