Node.js is highly versatile and has enabled developers to create a fast, reliable, and scalable web application with fewer lines of code. It was created by Ryan Dahl in 2009 by using the Google Chrome V8 JavaScript runtime environment.
The software application development landscape is continuously evolving and that has kept the Node.js development service providers on their toes. However, the introduction of Node js web development has brought much relief to the developer's community.
Node.js and its modules have collectively simplified the development of applications. As we mentioned earlier, Node.js is highly versatile because it allows developers to create an application on both the client and server at the same time.
There are over a quarter of a million modules (35K modules) to choose from. Node.js makes it extremely easy to develop a working application that can be easily scaled. If you want to build robust and scalable Node.js apps, here are 7 Node.js tips and tricks that every JavaScript developer ought to know.
Node.js Tips and Tricks for JavaScript Developers
1. Understanding the Mighty Event Loop
The event loop is what makes the Node so fast and brilliant. It helps the Node utilize the time efficiently which otherwise would have been wasted while waiting for input and output tasks to complete. The event loop is what makes the Node great at optimizing I/O-bound systems.
If your Node.js app needs to perform something CPU-intensive for example computation, hashing of passwords or compressing, then besides the usual task of spawning new processes for CPU-tasks, you will also require to explore options for deferring of the task with setImmediate() or setTimeout(). The code in their callbacks will continue on the next event loop cycle. Unfortunately, nextTick() works on the same cycle contrary to the name.
2. Use Built-In Debugger - Node Debug
If you are coming from a language with heavy IDE integration like Java or C#, debugging Node.js apps could get quite confusing. Many Node.js developers resort to using the “flow” debugging pattern by making use of console.log.
However, there are better alternatives that are more convention to debug Node.js apps. For example, Node.js comes packed with its own built-in debugger that you can run by calling node to debug. Node-inspector is also another interesting tool to debug your Node.js apps.
According to a GitHub report, Node Inspector is a debugger interface for node.js while using Blink Developer Tools (former WebKit Web Inspector). You can use node-inspector to debug your applications using any editor of your choice and chrome web tools.
You can do some really interesting stuff with Node-inspector such as live code changing, step debugging, and scope injection.
3. Use npm Scripts
Developers create npm scripts for builds, tests, and to even start the app. This has become almost a standard now. Naturally, this is also the first place developers look for when they encounter a new Node project. Other than this, you could also take a look at other front-end development tools.
Many developers have ditched Grunt, Gulp, and the likes in favor of more low-level but more dependable npm script and there is understandable reasoning behind it which we will save for the next blog post. However, here we will point to that fact that npm scripts have pre and post hooks which can help you handle the very sophisticated level of automation:
"scripts": {
"preinstall": "node prepare.js",
"postintall": "node clean.js",
"build": "webpack",
"postbuild": "node index.js",
"postversion": "npm publish"
}
While developing the front-end, often you must have come across a scenario where you wanted to run two or more watch processes to rebuild your code. Take for example you wanted one for Webpack and another for nodemon. You can easily achieve this with the help of && because the first command will not release the prompt.
To handle this situation, there is a module called Concurrently that can spawn multiple processes and run them all at the same time. You can also install dev command-line tools such as Webpack, nodemon, gulp, Mocha, locally to avoid conflicts.
4. Nodefly to Gauge the Performance
After developing the node.js app and once it is up and running, you will want to check its performance to make sure it is running at optimum speed. It’s a logical step for any developer to monitor their node.js app’s performance and profile. You can easily monitor the performance and profile of node.js apps by using the service called Nodefly.
With few lines of code, Nodefly will start to monitor the application for issues like memory leaks, and measure how long it takes for Redis, mongo queries, and quite a few other important stuff.
5. Start to Use Functional Inheritance
JavaScript makes use of prototypal inheritance whereby objects inherit from other objects. This is interesting and simplifies many things. The class operator also comes bundled with the language with ES6.
But the fact remains the same that it is overly complex compared to functional inheritance. Even though many Node experts prefer the simplicity of the latter. It can be implemented by a simple function factory pattern. It does NOT require the use of prototype, new or this.
Also, there are no implicit effects when you update the prototype which causes all the instances to change as well. This is because in functional inheritance each object makes use of its own copy of methods.
Here is a code from TJ Holowaychuk, the genius behind Express, Mocha, Connect, and dozens of other Node modules. The source code describes the uses of functional inheritance. You can check out the full source code here.
// ...
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
app.request = { __proto__: req, app: app };
app.response = { __proto__: res, app: app };
app.init();
return app;
}
6. Be Careful With node_modules Folder
Many developers aren’t aware that they should not be checking their node_modules folder. Many learn this the hard way. In fact, there is no reason for you to check this folder. Think of a scenario where someone checks your source out and at the same time run npm install and download all the modules required.
You may think, it’s not a big deal if you check in node_modules or anyone else does. That’s because from the surface nothing may appear wrong. But if the person checking out your source is on a different operating system (other than yours) and at the same time one of the modules that your app uses gets compiled when it’s installed via npm, the app will crash.
This happens because the modules like bcrypt and sentimental are compiled on the host system because they have native components written in C. The best way to avoid this situation is to completely avoid checking the node_modules folder.
7. Avoid Using JavaScript
You must be wondering what’s the point? That's because even with ES6 and other features added by ES2016/ES7, it still has its quirks. If you are open to exploring other options, you can highly benefit from minimal setup. Based on the requirement, expertise level and the nature of the app, you can do better with TypeScript or Flow which provides strong typing.
Some other options include Elm or ClojureScript which are purely functional. On the other hand, there is CoffeeScript which is another great option.
When you have a requirement for a few macros, not an entirely new language, you can consider Sweet.js. It does exactly what you want. It will allow you to write code that will generate code.
If you take the non-JavaScript route, you should still include the compiled code because developers may not understand your language well enough and therefore may not be able to build it properly.
Here is a quick example for you to understand. Think of the VS Code which is one of the largest TypeScript projects. It uses TypeScript to patch the Node’s core module with types. Therefore in the vscode/src/vs/base/node/ of VS Code repo, you will observe familiar module names like crypto, process, etc. yet with the ts extension. You will find other ts files in the repo. But, they included vscode/build with native JavaScript code.
Take away
In the age of open-source frameworks, there is no reason why we should not learn from the trusted and tested code that is in the public domain. Learning never stops and based on past failures and successes, best practices evolve.
We love exploring new things as much as we love sharing our knowledge. If you think you have some ideas that are worth sharing with our audiences, write in the comments below. If you have any questions or want to add something to this article, use the comment box below. Stay tuned to MobileAppDaily for daily updates in the mobile app world.
Sr. Content Strategist
Meet Manish Chandra Srivastava, the Strategic Content Architect & Marketing Guru who turns brands into legends. Armed with a Masters in Mass Communication (2015-17), Manish has dazzled giants like Collegedunia, Embibe, and Archies. His work is spotlighted on Hackernoon, Gamasutra, and Elearning Industry.
Beyond the writer’s block, Manish is often found distracted by movies, video games, AI, and other such nerdy stuff. But the point remains, If you need your brand to shine, Manish is who you need.