Loading...

Node js new protocol

Node js new protocol

Hey readers! So there is a new change in Node js which has been there for a while, that is the introduction of a new protocol in Node js. Do check out codedamn’s YouTube channel for more amazing videos and update. 

Now, what this protocol does is that when you use Node with a column and then something in front of it, you explicitly tell the JavaScript engine, in this the Node js engine that you want to use the official Node js module and not something which is being installed as an npm module. Let’s take an example to understand the reason behind this. Let’s assume there is a module allied fetch that is built into Node.

const fetch= require(‘fetch’);

If we do something like this, then it will work for sure because it is built into Node but what if I instead of this, install a conflicting Node module with the same name? What will happen? Which module will get imported? So the way JavaScript resolution Node module works is that it will try to look inside the module, your immediate Node module folder, then it will go ahead and try to look for the module in one directory up and will continue to do so until it finds the package or module.

mode_modules-> ../node_modules-> global modules folder

Similarly for fs which is a file system module if it had any malicious module or anything installed inside the node module then this fs would be imported as a module instead of the official one which in most cases we don’t want that. So to import an official module do something like this.

const fs= require(‘node:fs’);

console.log(fs) // you get the complete log of the module

This protocol will work automatically for Node 16 and above.

Benefits:

  1. Built-in Node module is imported
  2. No risk of overriding node modules
const fs= require(‘node:fs/promise’);

If you do something like this then it will import the promised version of this module.

Conclusion

If you like this blog then do check out this video on the codedamn YouTube channel with an in-depth explanation. If you have any queries or suggestions, do let us know in the comments! Check out the courses on Codedamn and practice coding in the Codedamn playgrounds.

Sharing is caring

Did you like what Agam singh, Aman Ahmed Siddiqui, Aman Chopra, Aman, Amol Shelke, Anas Khan, Anirudh Panda, Ankur Balwada, Anshul Soni, Arif Shaikh, wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far