Is there a way to get user input in terminal after npm start?

Viewed 272

Say I have a simple program that keeps running in the background. Here is a barebones simulation (index.js).

process.stdin.resume();
console.log('just hanging...')

Then run it with node index.js and there, nothing else happens till we just exit ctrl+c

However, you could still type in the terminal. Nothing actually happens but you are able to type.

Without propts can we read the input in our node project? A bit like in a textfield with font-end JavaScript?

2 Answers

I found the solution.

process.stdin.on('data',function(data){
    var entry = data.toString() 
    console.log(entry)

})

So as the process is running you're able to type into the terminal and once you hit enter, you can catch it as above data.toString() (of course the string itself captures the new line as well so it with \n at the end.

Whilst searching this I also learned that you can use the same idea instead of console.log

process.stdout.write(entry)

You can use your browser and inspect element, ctrl+shift+i in chrome. From there there is a console tab which you can use to see the output value

Related