
Over time, I learned a few useful facts while working with NodeJS that made my life much easier at the beginning. I tried to compile them into a list in this post. As a NodeJS developer, you may find at least some of these NodeJS tips helpful.
Using Strict Mode In Coding:
Using strict mode in Nodejs code helps us to figure out poorly written JavaScript syntax and forces 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.
Code language: JavaScript (javascript)
For example, in a javascript file without strict mode, you can initialize a new variable even without the ‘var’ keyword.
abcd = "some string value";
Code language: JavaScript (javascript)
It won’t result in any errors. But in the case of using ‘use strict’, it will throw an error like the below:
iterate = "some string value"
^
ReferenceError: abcd is not defined
Code language: JavaScript (javascript)
Thus, it forces you to write a little bit more structured code, which is very useful in generating quality code with a dynamic language like JavaScript.
Use Node shell:
If you are trying to test a NodeJS function on how it works, the NodeJS shell works a 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 fine. However, when you are done exiting the node shell, it doesn’t support ‘exit’/’quit’ or similar commands, just like other CLI tools. You must write a valid NodeJS statement that tells you to exit the process. Here is the command you will need for that.
$process.exit(0)
Code language: PHP (php)
On my first day of using NodeJS/shell, I had no idea how to exit the shell and had to Google to figure out how.
Using global variable As Cache:
If you are creating a comparatively small app and integrating a third-party caching mechanism would be an overhead, you can handle those right inside your NodeJS app, given that you are running it in a default single-threaded mode.
As a single-threaded application, only one instance of Nodejs is running(just like a desktop app) to process all requests, unlike other web programming languages, such as PHP/Ruby/Python. Declaring a global variable there persists and is accessible to all requests, so you should always be careful about that, too.
To achieve such a mechanism, create a global variable of the necessary types(JSON/array) and add the necessary manipulation mechanism for that variable inside your function. 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*/
}
Code language: JavaScript (javascript)
Easy Logging Without any third-party library:
We usually use the ‘console.log’ method for printing temporary info while developing and some good logging libraries for logging in the deployment stage. There’s good news if you are lazy enough and trying to avoid third-party logging libraries. You can still get a decent 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 about 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
Code language: PHP (php)
And you are set. The log file will contain all information, which can be checked later for useful information.
One more thing about the console object: we usually use the following format to print something to the terminal window:
console.log("I am trying to see the value of abc"+abc);
Code language: JavaScript (javascript)
It works for the single-valued item. For JSON/objects, we can use ‘console.log(ABC),’ but it won’t work with the ‘+’ operator. Here, we can use the ‘,’ separator to print different values:
console.log("I am trying to see the value of abc", abc);
Code language: JavaScript (javascript)
This may look obvious to some of you. But interestingly, I didn’t know or even try 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 always have the latest version. This is a good way to update all of your packages to their latest version, which might include several improvements, bug fixes, and new features. But this makes sense only as long as you are working only in development mode and the product isn’t in production yet. You can fix it if any compatibility occurs.
//instead of this:
"dependencies": {
"clustered-node": "*"
}
//use this
"dependencies": {
"clustered-node": "~0.0.10"
}
Code language: JavaScript (javascript)
However, in a production environment, having such a notation for dependencies is very risky. You never know which package will break when, and it could crash your app, too! So, use it in the earlier stage of development, but switch to a specific version-based dependency as soon as the product enters a major deployment stage.
Asynchronous looping:
We get useful support for asynchronous control flow/looping with underscoreJS/AsyncJS. However, it’s not hard to have it natively 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);
Code language: JavaScript (javascript)
Final Words:
This is not a completed post. Instead, it is supposed to be an ongoing list of small tips for beginners. If you have something to add, write it in the comments! Happy coding 🙂
Discover more from CODESAMPLEZ.COM
Subscribe to get the latest posts sent to your email.
This is a nice work, (Y)
exit node shell: CTRL+C, twice