A deeper introduction to Node.js (Part 1)

Salvador Guerrero
4 min readMar 25, 2020

This story dives a little deeper into node, if you would like a quick intro, I recommend reading my previous story A quick introduction to Node.JS.

Node.js uses the V8 JavaScript Engine used by Chrome, it compiles JavaScript using Just In Time (JIT) compilation instead of interpreting the code at runtime.

Node.js REPL

If you want to test something really quick without creating a file you can use Node.js REPL (Read Evaluate Print Loop) from the command line type node without any file and it will enter into REPL mode, I wont to into details but I do recommend reading more about it here, I personally like it because it has autocomplete, I can load files and everything that was typed can be saved into a file using .save.

Environment Variables

To send env variables when invoking node from the terminal you can prefix the command with the key-value pairs, example: NODE_ENV=debug node app.js, and you can access this env variable from code using process.env.NODE_ENV.

Send and read command line arguments

To send any number of arguments when invoking node from the terminal you can append them standalone or as key/value, example: node app.js sal or node app.js --name=sal, the arguments are then stored in the process.argv array on and after the third value as follows:

const args = process.argv.slice(2)
args[0] // will get the first arguments sent
// If it was a key/pair then use minimist library (passing the arguments using double dash --name=sal) and read the values as follows:
const args = require('minimist')(process.argv.slice(2))
args['name']

console module

The console module is used to print out to the terminal stdout that invoked node, it accept multiple parameters, strings objects and you can even pretty format strings, see the examples below:

// Print two variables
console.log(var1, var2)
// Format specifiers
// %s format a variable as a string
// %d format a variable as a number
// %i format a variable as its integer part only
// %o format a variable as an object
console.log('string1: %s and number1: %d', 'dog', 3)
// Clear's the terminal, behavior depends on the terminal/cmd
console.clear()
// Prints how many times a string has been printed with count()
// right next to the output
console.count('%o has been printed times:', var1)
// Print's the call stack trace
console.trace()
// Time how long something takes to finish
console.time('myFunction()')
myFunction()
console.timeEnd('myFunction()')
// Print to stderr, depending on the configuration it may not print
// to the terminal but print it to the error log
console.error('an error occurred')
// Color and style the output by installing a library called chalk
// $ npm install chalk
const chalk = require('chalk')
console.log(chalk.yellow('hi!'))
// Create a 10-step progress bar and every 100ms one step is
// completed. When the bar completes it clears the interval
// Install a package called progress
// $ npm install progress
const ProgressBar = require('progress')
const bar = new ProgressBar(':bar', { total: 20 })
const timer = setInterval(() => {
bar.tick()
if (bar.complete) {
clearInterval(timer)
}
}, 100)

readline module

To get input from the terminal (process.stdin) you use the readline module, I currently don’t know if they are other modules but I can see this module being used to read text files as well, below are some examples:

const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
readline.question(`What's your name?`, name => {
console.log(`Hi ${name}!`)
readline.close()
})
// For a more advance version, take a loot at Inquirer.js it lets
// you do many things like asking multiple choices, having radio
// buttons, confirmations, and more.

Exporting functionality

There are 3 ways to export objects from your scripts, there’s no better way to explain this than with examples:

const car = {
brand: 'Toyota',
model: 'Sienna'
}
///////////////////////////////////////
// 1st way
// Export the car directly into exports
///////////////////////////////////////
module.exports = car
///////////////////////////////////////
// 2nd way
// Export the car object as a property of exports
///////////////////////////////////////
exports.car = car
///////////////////////////////////////
// 3rd way
// Export the car object directly
///////////////////////////////////////
exports.car = {
brand: 'Toyota',
model: 'Sienna'
}

Exporting objects as properties is useful when exporting multiple objects from the same script.

Importing functionality

Using the export examples above, below I show how importing works:

///////////////////////////////////////
// 1st way
// If the object was exported directly into exports
///////////////////////////////////////
const car = require('./car')
///////////////////////////////////////
// 2nd way
// If the object was exported as a property of exports
///////////////////////////////////////
const car = require('./car').car
// or a mode detailed way
const multiple = require('./car')
multiple.car

That’s it for this story, I created these notes while learning from nodejs.dev, below I shared a script I used as a playground while writing this story, feel free to copy it and use it for your own learnings.

On the next story I will write about npm and node app configuration.

See y’all later ✌️

Node Playground Gist on GitHub

--

--

Salvador Guerrero
Salvador Guerrero

Written by Salvador Guerrero

Computer Science Engineer, Cross-Platform App Developer, Open Source contributor. 🇲🇽🇺🇸

No responses yet