A simple beginner’s guide to Node.Js and Npm (Part 2)

  • Through Callbacks: One of the most primitive and still widely used approaches.
function cb() {
console.log(new Date().toLocaleTimeString());
}
setInterval(cb, 1000);
  • Through Promises: The most decent and recommended method.
var promise = new Promise((resolve, reject) => {
setTimeout(()=>{
var time = new Date().toLocaleTimeString();
if(time) {
resolve(time);
} else {
reject(new Error("date error!"))
}
}, 3000);
});
promise.then(data=>{
console.log(data)
}).catch(err => {
console.error(err)
})
  • Through async/await: A more cleaner approach with limited coding. Works with promises, and totally eliminates the need of then() & catch() methods. It is very simple and easy to use.
async function timeout() {
var current = await promise;
console.log(current);
}
  • require(): It is built-in and can be used to include JavaScript functions/modules from different files. Whenever require() is used for a file, it will read and execute that file, and return its “exports” object.
exports.message = “This is demo 1.”;
var demo1 = require("./demo1.js");
console.log(demo1.message); //outputs: "This is demo 1."
import * as demo1 from "./demo1.js"; //here "*" used to import all objects
console.log(demo1.message); //outputs: "This is demo 1."
  • exports & module.exports: Both of these can be used to export any properties of the object. Initially both point to the same empty object.
module.exports.foo = “FOO”;exports.bar = “BAR”;
{“foo”: “FOO”, “bar”, “BAR”}
module.exports = {
message: "This is demo 1.",
display: fn()
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store