Node.js Development: Best Practices
Developers are often confused with the best practices in NodeJS while creating an application. Here are some useful tips that might help you.
The first thing to be considered is that keep the modules clean and simple, which makes it easier for further debugging and editing. It will be much easier to understand the code if it is written in a consistent style. It should include indent rules, variable naming conventions, comments etc.
It is a good practice to create package.json(npm package dependencies) file using npm init command. Also use –save every time you install a module, so that it can be added to the package.json file. Remember to include all npm packages used in your project to package.json file. Hence, developer can install all dependencies using npm install, no need to install them separately.
It is possible to start your NodeJS application by npm start command, Just put start command in script section of your project’s package.json file, just like this
"scripts": { "start": "node main.js" }
There is an easy way to find outdated versions of npm packages, just type
$ npm outdated and this will show the current, wanted and latest versions of the packages.
The best thing to consider while creating an asynchronous function is to set first parameter of the callback as an error flag.
eg:
module.exports = function (param1, callback) { // do something if( ! error){ // no errror callback(null, param2); // error-first callback return; } // if error callback(true,null); // error-first callback }
Always check for errors from callbacks, do not allow the underlying code to execute if there is any error. Node involves passing around lots of callbacks, and heavy use of higher-level functions to manage control flow. Using a functional style will save you a lot of trouble.
Using try… catch module with asynchronous functions may not end up with the desired results. Domains can catch asynchronous errors—for example, error events—which try/catch cannot do. Ref: https://nodejs.org/api/domain.html to read more about domain.
While you are creating a node application, always look for a good existing solutions first. Npm (https://www.npmjs.com) provides a lot of packages, there is a pretty good chance you will find the functionality that you are looking for.
The two most powerful aspect of Node.js are it’s non-blocking IO and asynchronous runtime. Both of these aspects of Node.js are what gives it the speed and robustness to serve more requests faster than any other language. So why should we go for the old-fashioned synchronous pattern?
// bad var data = fs.readFileSync('/path/to/file'); // synchronous console.log(data); // good fs.readFile('/path/to/file', function (err, data) { // asynchronous // err will be an error object if an error occurred // data will be the file that was read console.log(data); });
“use strict” behaviour flag which can be tagged as the header to any JavaScript file or function. This flag triggers error notification upon encountering bad practices with coding and even denies the usage of certain functions.
Never require Modules Inside of Functions: Node.js always runs require synchronously. This is so the module being required can require other needed modules. Always require modules at the top of your file, outside of any function call. Save the required module to a variable and use the variable instead of re-requiring the module. Node.js will save the module to that variable and your code will run much faster”.
eg:
var path = require('path'); // require module at the top module.exports = function xFunc(){ var newPath = path.join('/foo', 'bar', 'baz/asdf', 'quux'); // your stuff here } module.exports = function yFunc(){ var myPath = path.join('/koo’, 'yar', 'xaz/vgsdf'); // your stuff here }
Use environment variables to configure npm
“Any environment variables that start with npm_config_ will be interpreted as a configuration parameter. For example, putting npm_config_foo=bar in your environment will set the foo configuration parameter to bar. Any environment configurations that are not given a value will be given the value of true. Config values are case-insensitive, so NPM_CONFIG_FOO=bar will work the same.”
Ref: https://docs.npmjs.com/misc/config#environment-variables
One last thing to be noted is the difference between exports and module.exports. Exports only collects properties and attaches them if module.exports doesn’t already have existing properties. If the module.exports comes with any property, everything tagged with exports is ignored rather than the things attached to module.exports.
Hope you enjoyed reading this article.
Courtesy: Various internet resources