1

I am using vsCode for NodeJS.

My code was simple. So I was expecting stdout should wait for input from console. Once input is given, then it should go to exit.

But once i do > node process

the program goes to exit directly.

file - process.js ->

process.stdout.write('Ask me something : ');
process.stdin.on('data', function(answer){
console.log(answer.toString());   
});

console.log('exit')
process.exit();

Output:

 c:\node-projects\demo-nodejs>node process
 Ask me something : exit
 c:\node-projects\demo-nodejs>

How can I use process object to get standard input/output/print/exit the code instead of using other readline object?

stackuser83
  • 2,012
  • 1
  • 24
  • 41
Arasn
  • 138
  • 10

1 Answers1

2

There are a few question/answers such as this one already on this site that probably answer what you are asking. Your code is not working because the line with process.stdin.on is not a synchronous callback method call, it is an event handler that waits for the 'data' event.

If I understand what you are trying to do, I think it is easiest to import the 'readline' module. It is built-in to the nodejs executable, but not loaded to your code execution environment unless you require it.

That would make your code look like this:

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.question('Ask me something : ', function(answer){
    console.log(answer.toString());
    console.log('exit')
    process.exit();
});

Note that the rl.question method call executes right away and calls the function(answer) function when the user is done with text input. It can take some understanding and getting used to the asynchronous program control flow in NodeJS, you might have to rethink some of the rest of your program structure.

The offical documentation for the readline NodeJS module and function is here.

stackuser83
  • 2,012
  • 1
  • 24
  • 41