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 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.
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 forcing you to write a little bit more structured code. Which is very useful in generating quality code with such a dynamic language as 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 have support for ‘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 NodeJS/shell using, I 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 in a default single-threaded mode.
As being single-threaded, only one instance of Nodejs application is running(just like a desktop app) to process all requests, unlike other web programming languages PHP/ruby/python etc based apps. 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 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 filevar cache = {};
exports.someMethod = function(data){
/*Your business logic*///set cache
cache[key] = val;
//retrieve cache
cachedVal = cache[key];
//delete cachedelete 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 development and some good logging libraries for logging in the deployment stage. If you are lazy enough and trying to avoid third-party logging libraries, there’s good news for you. 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 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. All information will be logged in the log file, 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 ‘+’ operator. Here we can use ‘,’ 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 have the latest version always. It’s a good way to have all of your packages updated to their latest version, which might have several improvements, bug fixes, and new features included. But this makes sense 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.
However, in a production environment, it’s very, very risky to have such a notation for dependencies. You never know which package gonna break when, and it could cause crashing 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 becomes in a major deployment stage.
Asynchronous looping:
We get useful support for asynchronous control flow/looping with underscoreJS/AsyncJS. However, it’s not that 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:
This is not a completed post. Rather, it supposes to be an ongoing list of small tips for beginners. If you have something to add, write it in the comments! Happy coding 🙂
var JetpackInstantSearchOptions=JSON.parse(decodeURIComponent("%7B%22overlayOptions%22%3A%7B%22colorTheme%22%3A%22light%22%2C%22enableInfScroll%22%3Atrue%2C%22enableFilteringOpensOverlay%22%3Atrue%2C%22enablePostDate%22%3Atrue%2C%22enableSort%22%3Atrue%2C%22highlightColor%22%3A%22%23FFC%22%2C%22overlayTrigger%22%3A%22submit%22%2C%22resultFormat%22%3A%22expanded%22%2C%22showPoweredBy%22%3Atrue%2C%22defaultSort%22%3A%22relevance%22%2C%22excludedPostTypes%22%3A%5B%5D%7D%2C%22homeUrl%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%22%2C%22locale%22%3A%22en-US%22%2C%22postsPerPage%22%3A5%2C%22siteId%22%3A18994550%2C%22postTypes%22%3A%7B%22post%22%3A%7B%22singular_name%22%3A%22Post%22%2C%22name%22%3A%22Posts%22%7D%2C%22page%22%3A%7B%22singular_name%22%3A%22Page%22%2C%22name%22%3A%22Pages%22%7D%2C%22attachment%22%3A%7B%22singular_name%22%3A%22Media%22%2C%22name%22%3A%22Media%22%7D%7D%2C%22webpackPublicPath%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-content%5C%2Fplugins%5C%2Fjetpack%5C%2Fjetpack_vendor%5C%2Fautomattic%5C%2Fjetpack-search%5C%2Fbuild%5C%2Finstant-search%5C%2F%22%2C%22isPhotonEnabled%22%3Afalse%2C%22isFreePlan%22%3Atrue%2C%22apiRoot%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-json%5C%2F%22%2C%22apiNonce%22%3A%22155bc22a78%22%2C%22isPrivateSite%22%3Afalse%2C%22isWpcom%22%3Afalse%2C%22hasOverlayWidgets%22%3Afalse%2C%22widgets%22%3A%5B%5D%2C%22widgetsOutsideOverlay%22%3A%5B%5D%2C%22hasNonSearchWidgets%22%3Afalse%2C%22preventTrackingCookiesReset%22%3Afalse%7D"));
heyuou@hey.com says
This is a nice work, (Y)
nobody says
exit node shell: CTRL+C, twice