Given the following complete program, test-readFile-utf8:
#!/usr/bin/env node
var fs = require("fs");
fs.readFile("/dev/stdin", "utf8", function(error, contents) {
console.log(contents.length);
});
And given an input file test.txt of 100,000 bytes, the following behaves as expected:
$ ./test-readFile-utf8 < test.txt
100000
However, if the test file is piped using cat, the program fails to read the entire file:
$ cat test.txt | ./test-readFile-utf8
65536
A complete set of test cases are available here: http://bl.ocks.org/mbostock/52950e1e53c19a56fad3
This problem can be avoided by using process.stdin’s data and end events:
#!/usr/bin/env node
var chunks = [];
process.stdin
.on("data", function(chunk) { chunks.push(chunk); })
.on("end", function() { console.log(chunks.join("").length); })
.setEncoding("utf8");
However, it’s often convenient to have a single code path for reading input either from a file or from stdin — and it’s surprising that fs.readFile("/dev/stdin") (and likewise fs.readFileSync("/dev/stdin")) work sometimes but not other times — so it would be nice to make these methods work all the time as expected.