Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Accept Input from Command Line
3.
Output To the Command Line
3.1.
Output:
3.2.
Clearing the Console
3.3.
Counting Elements
3.4.
Reset Counting
3.5.
Print the Stack trace
3.6.
Calculate the time spent
3.7.
Stdout and Stderr
3.8.
Color the output
3.9.
Create a progress bar
4.
Frequently asked questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

Node.js input and output - command line

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

 To begin with, the official node.js documentation defines it as,

“Node.js is a platform built on Chrome’s Javascript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.”

Apart from the formal definition, some crucial points about node.js are:

  • It is an open-source server environment
  • Node.js applications are written in JavaScript and run on various platforms like Windows, Linux, Unix, Mac OS X.
  • It uses JavaScript on the server.
  • It is neither a framework nor a programming language
  • We use it to develop server-side and networking applications. 
     

Now that we know about node.js, let's learn how node.js input and output from the command line works.

Accept Input from Command Line

To get input from a readable stream for example the process.stdin stream, which is the terminal input during the execution of a Node.js program, one line at a time.


const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
})

readline.question(`What is your name?`, name => {
  console.log(`Hello ${name}!`)
  readline.close()
})

 


Output:

The code that you just went through asks the user for the username and once entered we send out a greeting.

The first parameter (the question) is shown out by the question() method and it waits for the user to enter the input.It then calls the callback function once the enter key is pressed.

The readline interface is closed in this callback function. 

Another package that can help us to take input from command line is inquirer. 

A example code is mentioned in the code below :

const inquirer = require('inquirer')

var questions = [
  {
    type: 'input',
    name: 'name',
    message: "What's your name?"
  }
]

inquirer.prompt(questions).then(answers => {
  console.log(`Hi ${answers['name']}!`)
})


Output:

You can ask multiple choices, have radio buttons, confirmations and much more using inquirer.js

 

Let’s quickly have a look at the output to the command line as well that we can provide using node.js.

Also see, Difference Between Controller and Restcontroller

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Output To the Command Line

We have tons of useful ways to interact with the command line using the console module that is provided to us by Node.js.

This turns out to be something similar to the console object we find in the browser.

The most used and the most basic method is the console.log(), This basically prints the string that we pass to it to the console.

If we pass an object, it will then render it as a particular string.

We can pass multiple variables to console.log, for example:

const a = 'a'
const b = 'b'
console.log(a, b)


Output:

Using this Node.js will print out both.

By passing the variables and a format specifier we can also format the pretty phrases.

For Example :

console.log('My %s has %d ears', 'cat', 2)

Output:

Let’s see what all things are being used in the code above :

  • %s is used to format a variable as a string
  • %d is used to format a variable as a number
  • %i is used to format a variable as its integer part only
  • %o is used to format a variable as an object
console.log('%o', Number)

Output:

Clearing the Console

console.clear() is used to clear the console and the behavior depends on the console that we use.

Counting Elements

If we tend to count elements we can use a handy function called console.count() to get our job done.

Let’s have a look at this code :

const a = 1
const b = 2
const c = 3
console.count(
  'The value of a is ' + a + 
  ' and has it been checked how many times?'
)
console.count(
  'The value of a is ' + a + 
  ' and has it been checked how many times?'
)
console.count(
  'The value of b is ' + b + 
  ' and has it been checked how many times?'
)


Output

The value of a is 1 and has it been checked how many times?: 1
The value of a is 1 and has it been checked how many times?: 2
The value of b is 2 and has it been checked how many times?: 1


So basically console.count() checks the count of the number of times the string is printed and then it directly prints the count next to it.

We can use the same and count bananas and mangos:

const Mangos = ['Mangos', 'Mangos']
const bananas = ['just one bananas']
Mangos.forEach(fruit => {
  console.count(fruit)
})
bananas.forEach(fruit => {
  console.count(fruit)
})


Output:

Reset Counting

We can now use console.countReset() and reset the counter that we used with the console.count(). 

We will use the same example of mangos and bananas to implement this.

const mangos = ['mangos', 'mangos']
const bananas = ['just one bananas']
mangos.forEach(fruit => {
  console.count(fruit)
})
bananas.forEach(fruit => {
  console.count(fruit)
})

console.countReset('mangos')

mangos.forEach(fruit => {
  console.count(fruit)
})


Output:

And here the call to console.countReset() basically sets the counter to zero.

Print the Stack trace

We tend to fall into cases where it is completely useful to print the call stack trace of a function,

Let’s see how we can use the console.trace() : 

const function2 = () => console.trace()
const function1 = () => function2()
function1()


This will now help us by printing the stack trace. We can also try this in the Node.js REPL and this is what we will get then:

Trace
    at function2 (repl:1:33)
    at function1 (repl:1:25)
    at repl:1:1
    at ContextifyScript.Script.runInThisContext (vm.js:44:33)
    at REPLServer.defaultEval (repl.js:239:29)
    at bound (domain.js:301:14)
    at REPLServer.runBound [as eval] (domain.js:314:12)
    at REPLServer.onLine (repl.js:440:10)
    at emitOne (events.js:120:20)
    at REPLServer.emit (events.js:210:7)

 

Calculate the time spent

We can also calculate the time a function takes to run very easily using the time() and the timeEnd(). Let’s have a look at the code for the same:


const timetesting = () => console.log('test')
const measureTimeTesting = () => {
  console.time('timetesting()')
 
  timetesting()
  console.timeEnd('timetesting()')
}
measureTimeTesting()


Output:

Stdout and Stderr

So we used the console.log to print messages in the console and this is what we call the standard output or stdout.

Also,

console.error() prints directly to the stderr stream

And the main part about this is that it will never appear in the console but will appear in error log.

Color the output

We often wish to color the output of our text and we can easily do it using the escape sequences. It is basically a set of characters that help us by identifying a specific color. Let’s understand this with the help of an example:

console.log('\x1b[33m%s\x1b[0m', 'hello!')


Output:

This code will give us a direct output of “hello!” in yellow color.

But we can say that this is a very low-level way to do this. We can use a simpler way to do the same thing and that is by using a library. The name of this library is Chalk, and it not only colors but also helps us to style our output by making text bold, italic and also underline it.

We can install it using npm install chalk and use it in the below mentioned way:

import chalk from 'chalk';

console.log(chalk.green("Welcome To"))
console.log(chalk.bold("Coding Ninja"))
console.log(chalk.blue('Hello world!'));


Output:

Using the chalk.green and chalk.bold command we conveniently get our job done rather than worrying about the escape codes and this code is also pretty much easily readable

Create a progress bar

We have another fabulous package that helps us create a progress bar in the console. We can install it by using npm install progress.

This basically is a snippet of code that creates a 10-step progress bar, and after a time interval of 100ms one step gets completed. As soon as the bar gets completed we successfully clear the interval:


import ProgressBar from 'progress';
 
var bar = new ProgressBar(':bar', { total: 10 });
var timer = setInterval(function () {
  bar.tick();
  if (bar.complete) {
    console.log('\ncomplete\n');
    clearInterval(timer);
  }
}, 100);


Output:

Finally after a deep study of the node.js input and output statements let's have a look at the frequently asked questions by people on the topic.

Frequently asked questions

1. Is Node JS frontend or backend?

Node.js can be used in both the frontend and backend of applications and websites, thereby making the work of developers easier.

2. Is Node JS a programming language?

No, we can say that node.js is not a programming language, it allows developers to use JavaScript, a programming language for creating web applications. 

3. Name some companies that use Node.js.

Some companies that use node.js are eBay, PayPal, Yahoo, Microsoft, and Uber.

4. List some advantages of using Node.js.

Some advantages of Node.js are:

  • Easy Scalability
  • Real-time web apps 
  • Fast Suite
  • Easy to learn and code
  • Caching
  • Data Streaming
  • Corporate Support

Key Takeaways

In this article we were able to understand the node.js input and output commands.We discussed node.js input and output in detail. We also discussed some frequently asked question about node.js input and output.

This doesn’t seem enough, though.

Of course not!

Whether it is frontend or backend or even both with node.js, Web development is all about learning by doing. You can now check out this course on Full Stack Development, which includes tutorials on Node.js.

Recommended Readings:

NPX vs NPM

Happy Learning!

Previous article
Advantages and Disadvantages of Node.js
Next article
Understanding the Node Architecture
Live masterclass