【问题标题】:NodeJS: Send EOF to stdin stream without closing streamNodeJS:将 EOF 发送到标准输入流而不关闭流
【发布时间】:2012-06-01 00:05:58
【问题描述】:

如何在不关闭流的情况下向流发送 EOF 信号?

我有一个脚本等待 stdin 上的输入,然后当我按下 ctrl-d 时,它会将输出吐出到 stdout,然后再次等待 stdin,直到我按下 ctrl-d。

在我的 nodejs 脚本中,我想生成该脚本,写入标准输入流,然后以某种方式发出 EOF 信号而不关闭流。这不起作用:

var http = require('http'),
    spawn = require('child_process').spawn;

var child = spawn('my_child_process');
child.stdout.on('data', function(data) {
    console.log(data.toString());
});

child.stdout.on('close', function() {
    console.log('closed');
})

http.createServer(function (req, res) {
    child.stdin.write('hello child\n');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

但是如果我将 child.stdin.write(...) 更改为 child.stdin.end(...),它可以工作,但只有一次;之后流关闭。我在某处读到 EOF 实际上不是一个字符,它只是任何不是字符的东西,通常是 -1,所以我尝试了这个,但这也不起作用:

var EOF = new Buffer(1); EOF[0] = -1;
child.stdin.write("hello child\n");
child.stdin.write(EOF);

【问题讨论】:

  • 我很确定这是不可能的。见stackoverflow.com/questions/9633577/…
  • 为什么不能直接关闭输入流?我在这里很困惑。
  • 因为我想再次写入标准输入。该进程等待 EOF,然后在输入上分块,然后重新打开 /dev/stdin 以等待更多。
  • 这似乎与 unix 的概念大相径庭,谁编写了另一个进程?
  • 我写的。这是一个 PhantomJS 脚本。看来我可能得重新设计了。不过,这并非史无前例。 Python、C、C++ 和其他可能的程序员也想知道同样的事情。

标签: javascript node.js


【解决方案1】:

你试过child.stdin.write("\x04");吗?这是Ctrl+D的ASCII码。

【讨论】:

  • 这是跨平台的吗?这也适用于 Windows 吗?
  • 我不确定。问答早于 Windows 上的 node.js 支持;我从未在 Windows 环境中运行过 node.js。 Ctrl+D 是 Windows 中的信号吗?
【解决方案2】:

你用res 做到了,就在下面两行...

  • stream.write(data) 用于你想继续写的时候
  • stream.end([data]) 用于不需要发送更多数据(它会关闭流)
var http = require('http'),
    spawn = require('child_process').spawn;

var child = spawn('my_child_process');
child.stdout.on('data', function(data) {
    console.log(data.toString());
});

child.stdout.on('close', function() {
    console.log('closed');
})

http.createServer(function (req, res) {
    child.stdin.end('hello child\n');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

【讨论】:

    【解决方案3】:
    var os = require("os");    
    child.stdin.write("hello child\n");
    child.stdin.write(os.EOL);
    

    我在我的项目中使用它并且它有效

    【讨论】:

    • EOF != EOL。 EOL 在 Windows 上可能是 \r\n,在 Linux 上可能是 \n。
    • @joonas.fi yupp
    猜你喜欢
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    相关资源
    最近更新 更多