DEV Community

miku86
miku86

Posted on • Edited on

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
Enter fullscreen mode Exit fullscreen mode
  • 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}`);
});
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

Console.log() uses stdout under the hood.

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

Documentation for readable stream

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

Run it from the terminal

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

Questions

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

Top comments (0)