Node globals-Node.js essential knowledge 1

Haifeng Wang
3 min readOct 13, 2020

Node.js is a open source project in Github, created by Ryan Dahl in 2009, as a Javascript Runtime based on Chrome’s v8 Engine, so the applications for Node are written in Javascript. Node is lightweight and we can write frontend and backend in the same language, share libraries, reduce code write times.

Install Node.js, go to nodejs.org to download the Nodejs, after installing in the system, type node -v in terminal to verify if it’s installed right.

Node globals

It’s time to create our first Node.js file, create a js file. Run the command, node yourfirstjs.js, it will run, if leave off the .js extension, it will run too because node assumes that it’s a javascript file.

The console object is actully a part of global object, we could prefix this with global: global.console.log(“this is the first nodejs file”)

nodejs.org/api/globals.html

requre("path")
console.log(__dirname);
console.log(__filename);

Nodejs also comes with some tools that will allow us to edit and manipulate filepaths, but we have to load these tools because they come in a separate module. path gives us tools that we can use to help us work with path strings. We can use basename() to pluck the filename onlyf from global _filename variable.

Another important object that’s available to us globally isthe process object. Which can be accessed globally and it contains information about the current process as well as tools to allow us to interact with that process. We use the process.argv array to pass arguments to Node.js module when we run the process.

#example 1
console.log(process.pid)
console.log(process.versions.node)
#example 2
const [, , firstname, lastname] = process.argv;
console.log(`the name is ${firstname} ${lastname}`)
#using tags to mark what variables we are passing
const grab = flag => {
let indexAfterFlag = process.argv.indexOf(flag) + 1;
return process.argv[indexAfterFlag];
}
const greeting = grab("--greeting")
const user = grab("--user")
console.log(`${greeting} ${user}`)

Aother feature of the process object is standard input and standard output. There two objects offer us a way to communicate with this process while it’s running. This is the example of working with Node.js asynchronously by using event listeners.

const questions = [
"What is your name?",
"what would you rather be doing?",
"What is your preferred programming language"
]
const ask = (i = 0) => {
process.stdout.write(`\n\n ${questions[i]}`);
process.stdout.write(` > `);
}
ask();
const answers = [];
// Use standard input object to listen for the answer
process.stdin.on("data", data => {
answers.push(data.toString().trim());
if (answers.length < questions.length) {
ask(answers.length);
} else {
process.exit();
}
})
process.on("exit", () => {
console.log("here is the overview");
const [name, activity, language] = answers;
console.log(`Hi ${name}, do some ${activity}, program ${language} later`)
})

Another way we can work with node.js asynchronously-set timing:

const waitTime = 3000;const waitInterval = 500;let currentTime = 0;const incTime = () => {currentTime += waitInterval;console.log(`wait for ${currentTime / 1000}`);
}
console.log(`setting up a ${waitTime / 1000} seconds delay`);const timeFinished = () => {clearInterval(interval);console.log(`done`);
}
// If I have to clear the interval, need to have a variable for the interval
const interval = setInterval(incTime, waitInterval);
setTimeout(timeFinished, waitTime);

Report progress with setInterval:

const waitTime = 3000;const waitInterval = 500;let currentTime = 0;const incTime = () => {currentTime += waitInterval;const p = Math.floor((currentTime / waitTime) * 100)process.stdout.clearLine();process.stdout.cursorTo(0);process.stdout.write(`waiting ... ${p}%`)}console.log(`setting up a ${waitTime / 1000} seconds delay`);const timeFinished = () => {clearInterval(interval);process.stdout.clearLine();process.stdout.cursorTo(0);console.log(`done`);}// If I have to clear the interval, need to have a variable for the intervalconst interval = setInterval(incTime, waitInterval);setTimeout(timeFinished, waitTime);

--

--