NodeJS: How To Talk/Answer To The Terminal

Intro

So we installed NodeJS on our machine.

Now we want to write a simple script, run it from the terminal & talk/answer to the terminal


Write a simple script

  • Open your terminal
  • Create a file named index.js:
touch index.js
  • Add this JavaScript code into it:
process.stdout.write("What's your name?\n");

process.stdin.on("readable", () => {
  const userInput = process.stdin.read();
  process.stdout.write(`Your Input was: ${userInput}`);
});

Note: I removed all "unnecessary" stuff from the documentation to decrease the complexity of this simple example.


Every line decoded

// writes something to the stdout (your terminal), including a newline at the end
process.stdout.write("What's your name?\n");

Console.log() uses stdout under the hood.

// if a specific event (here: a readable stream) happens, then run this  callback
process.stdin.on('readable', () => {...});

Documentation for readable stream

// read data from the stream & save it into a variable
const userInput = process.stdin.read();
// writes something to the stdout
process.stdout.write(`Your Input was: ${userInput}`);

Run it from the terminal

  • Run it:
node index.js
  • Result:
What`s your name?
miku86
Your Input was: miku86

Questions

  • Do you use the native process.stdin or some libraries like inquirer or prompts? Why?