Over time, I learned a few useful facts while working with NodeJS that made my life a lot easier at the beginning stage. I tried to compile them into a list on this post. As a NodeJS developer, you may find at least some of these NodeJS tips helpful as well.
Using Strict Mode In Coding:
using strict mode in Nodejs code, helps us to figure out poorly written JavaScript syntax and enforces us to write better code syntax. To use this, just add the following line in every JavaScript file you create/write code on:
'use strict'; //rest of your NodeJS code goes here.
For example, in a javascript file without strict mode, you can initialize a new variable even without the ‘var’ keyword.
abcd = "some string value";
It won’t result in any error. But in case of using ‘use strict’, it will throw a error like below:
iterate = "some string value" ^ ReferenceError: abcd is not defined
Thus enforcing you to write little bit more structured code. Which is very useful in generating quality code with such a dynamic language like JavaScript.
Use Node shell:
If you are trying to test a nodejs function how it works, nodejs shell works lot better for that. Just run ‘node’ and it will bring you up the node shell. write code just like in a text editor and it will work just fine. However, when you are done, to exit the node shell, it doesn’t have support for ‘exit’/’quit’ or similar commands just like other cli tools. You have to write a valid NodeJS statement that tells to exit the process. Here is the command you will need for that.
$process.exit(0)
On my first day of nodejs/shell using, I literally had no idea how to exit the shell and had to google to figure out this way.
Using global variable As Cache:
If you are creating a comparatively small app where it will be an overhead to integrate a third-party caching mechanism, you can handle those right inside your NodeJS app, given that you are running it as a default single threaded mode.
As being single threaded only one instance of Nodejs application is running(just like an desktop app) to process all requests. Which is unlike other web programming language php/ruby/python etc based app. Declaring a global variable there persists and accessible to all requests. So, you should always be careful about that too.
To achieve such mechanism, create global variable of necessary types(json/array) and inside your function add necessary manipulation mechanism for that variable. it will persist across all requests.
'use strict'; //this is your cache for this js file var cache = {}; exports.someMethod = function(data){ /*Your business logic*/ //set cache cache[key] = val; //retrieve cache cachedVal = cache[key]; //delete cache delete cache[key]; /*Your business logic*/ }
Easy Logging Without any third-party library:
We usually use ‘console.log’ method for printing temporary info while development and some good logging libraries for logging
in deployment stage. If you are lazy enough and trying to avoid third-party logging libraries, there’s a good news for you. You can still get a descent logging system on your nodejs app with native support.
The ‘console’ object in NodeJS has several different levels for logging(error/info/warn etc), which you can check more here on the console object’s official documentation page. Use them appropriately as needed. Then, while running the nodejs app, refer to a log file where you want everything written as below:
$node app.js > mylog.log
And you are set. All information will be logged in the log file, which can be checked later for useful information.
One more thing about console object, we usually use the following format to print something to terminal window:
console.log("I am trying to see the value of abc"+abc);
It works for single valued item. For json/objects, we can use ‘console.log(abc)’ , but won’t work with ‘+’ operator. Here we can use ‘,’ separator to print different values:
console.log("I am trying to see the value of abc", abc);
This may look obvious to some of you. But interestingly, I didn’t knew or even tried this for my first few days of nodejs. So, other beginners might find this useful.
Avoid using “*” in production dependency:
In your package.json file, you can specify a version to use or keep ‘*’ to have a latest version always. It’s a good way to have all of your packages updated to their latest version which might have several improvement, bug fixes, new features included. But this makes good sense as long as you are working only in development mode and the product isn’t in production yet. You can fix if any compatibility occurs.
//instead of this: "dependencies": { "clustered-node": "*" } //use this "dependencies": { "clustered-node": "~0.0.10" }
However, in production environment, it’s very very risky to have such notation for dependencies. You never know which package gonna break when and could cause crashing your app too! So, use it in the earlier stage of development, but switch to specific version based dependencies as soon as product becomes in a major deployment stage.
Asynchronous looping:
We get some very useful support for asynchronous control flow/looping with use of underscoreJS/AsyncJS. However, it’s not that hard to have it natively as well, as long as you understand the callback concepts well. So, in case you don’t want to use such libraries for a simple task, you can use the following mechanism:
var iterate = function(items, i){ console.log("handling: "+i); //async methods etc someAsyncMethod(params, function callback(){ if(items.length <= i)return; return iterate(items, ++i); }) }; var items = [1,2,3,4]; iterate(items, 0);
Final Words:
This is not a completed post. Rather, it suppose to be an ongoing list of small tips for beginners. If you have something to add, write it in the comments! Happy coding 🙂
This is a nice work, (Y)
exit node shell: CTRL+C, twice