Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger event stdin.on("data", [callback]) in the code?

Tags:

node.js

Consider the following example

process.stdin.resume();
process.stdin.on("data", function(data) {
  console.log("recieved " + data)
})

process.stdin.write("foo\n")
process.stdin.write("bar\n")

When I type something in terminal, I get

 received something

Why it doesn't work in the same way for foo and bar which I sent earlier using stdin.write?

E.g. how can I trigger this event (stdin.on("data)) in the code? I was expected process.stdin.write to do this, but I'm just getting the same output back.

like image 867
evfwcqcg Avatar asked Jan 18 '13 19:01

evfwcqcg


People also ask

What is process Stdin on in JavaScript?

The process. stdin property is an inbuilt application programming interface of the process module which listens for the user input. The stdin property of the process object is a Readable Stream. It uses on() function to listen for the event.

What is stdin and stdout in NodeJS?

stdin (0): The standard input stream, which is a source of input for the program. process. stdout (1): The standard output stream, which is a source of output from the program. process. stderr (2): The standard error stream, which is used for error messages and diagnostics issued by the program.

How do I stop a process from using Stdin?

`process. stdin. pause` will "close" `stdin`.

What is process CWD?

process. cwd() returns the current working directory, i.e. the directory from which you invoked the node command. __dirname returns the directory name of the directory containing the JavaScript source code file.


1 Answers

It's a Readable Stream that gets its input from the stdin file descriptor. I don't think you can write into that descriptor (but you could connect it to another writable descriptor).

However, the easiest solution in your case it to just simulate the 'data' events. Every stream is an EventEmiiter, so the following will work:

process.stdin.resume();
process.stdin.on("data", function(data) {
   console.log("recieved " + data)
});

process.stdin.emit('data', 'abc');
like image 81
nimrodm Avatar answered Oct 04 '22 01:10

nimrodm