#!/usr/bin/env node
function stdinReadSync() {
var b = new Buffer(1024);
var data = '';
while (true) {
var n = require('fs').readSync(process.stdin.fd, b, 0, b.length);
if (!n) break;
data += b.toString(null, 0, n);
}
return data;
}
var s = stdinReadSync();
console.log(s.length);
如果您使用 echo
、cat
、ls
提供上述代码(取自 Stackoverflow),则可以正常工作,但如果使用 curl
输出,则会失败。
$ echo abc | ./test.js
4
$ ls | ./test.js
1056
$ cat 1.txt | ./test.js
78
$ curl -si wikipedia.org | ./test.js
fs.js:725
var r = binding.read(fd, buffer, offset, length, position);
^
Error: EAGAIN: resource temporarily unavailable, read
at Error (native)
at Object.fs.readSync (fs.js:725:19)
at stdinReadSync (/home/ya/2up/api/stdinrd.js:8:29)
at Object.<anonymous> (/home/ya/2up/api/stdinrd.js:15:9)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
at Function.Module._load (module.js:407:3)
at Function.Module.runMain (module.js:575:10)
(23) Failed writing body
为什么?如何修复?
最佳答案
这有点像黑客,但这似乎有效:
var n = require('fs').readSync(0, b, 0, b.length);
我认为(纯粹猜想)process.stdin.fd
是一个 getter,当被引用时,会将 stdin 置于非阻塞模式(这导致了错误)。当您直接使用文件描述符时,您可以解决这个问题。
关于node.js - 标准输入读取某些输入失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40362369/