← back to the blog


4 NodeJS useful things to know

Posted on April 15th, 2020 in NodeJS by George

 

1. Run Javascript code from an URL using npx

npx https://gist.github.com/GeorgeCrisan/7675f32e10dba82d54381553ecf4e141

//Output

I love to work with JavaScript

 

2. Use 'npx' to run JavaScript code on different node versions without need of nvm

// type npx / node version / code to execute(or file)

➜  ~ npx node@8 -v
v8.17.0

➜  ~ npx node@12 -v
v12.16.2

➜  ~ node -v
v12.16.0

npx node@8 index.js   

 

3. Locate in the global node_modules files in your system

//Type in terminal
npm root -g

//Output example
/usr/local/lib/node_modules

 

4. Execute async code as soon as possible(but after the current function execution)

You may have used in the past this hack.

setTimeout(() => {}, 0);

When you want to execute some piece of code as soon as possible, use setImmediate() is just before the hack above and immediately after the process.nextTick(), from the event loop point of view.


setImmediate(() => {
  //run something
  console.log(`So nice to work with JavaScript`);
});

 

Thank you and stay safe.