为什么我得到 process.stdin undefined
Why I get process.stdin undefined
我想用下面的代码做一个简单的地图(唯一重要的部分是最后两行)
/**
* Mapper chunk processing function.
* Reads STDIN
*/
function process () {
var chunk = process.stdin.read(); // Read a chunk
if (chunk !== null) {
// Replace all newlines and tab chars with spaces
[ '\n', '\t'].forEach(function (char) {
chunk = chunk.replace(new RegExp(char, 'g'), ' ');
});
// Split it
var words = chunk.trim().split(' ');
var counts = {};
// Count words
words.forEach(function (word) {
word = word.trim();
if (word.length) {
if (!counts[word]) {
counts[word] = 0;
}
counts[word]++;
}
});
// Emit results
Object.keys(counts).forEach(function (word) {
var count = counts[word];
process.stdout.write(word + '\t' + count + '\n');
});
}
}
process.stdin.setEncoding('utf8');
process.stdin.on('readable', process); // Set STDIN processing handler
但我收到以下错误:
process.stdin.setEncoding('utf8');
^
TypeError: Cannot read property 'setEncoding' of undefined
我根本无法理解它的原因,而且我在 Internet 上找不到任何关于此的信息。为什么我的 process.stdin 未定义?有什么想法吗?
您使用名为 process
的函数隐藏了 process
模块。
我相信你调试它的最佳尝试是 console.log(process)
并发现它看起来不像你期望的那样。
我想用下面的代码做一个简单的地图(唯一重要的部分是最后两行)
/**
* Mapper chunk processing function.
* Reads STDIN
*/
function process () {
var chunk = process.stdin.read(); // Read a chunk
if (chunk !== null) {
// Replace all newlines and tab chars with spaces
[ '\n', '\t'].forEach(function (char) {
chunk = chunk.replace(new RegExp(char, 'g'), ' ');
});
// Split it
var words = chunk.trim().split(' ');
var counts = {};
// Count words
words.forEach(function (word) {
word = word.trim();
if (word.length) {
if (!counts[word]) {
counts[word] = 0;
}
counts[word]++;
}
});
// Emit results
Object.keys(counts).forEach(function (word) {
var count = counts[word];
process.stdout.write(word + '\t' + count + '\n');
});
}
}
process.stdin.setEncoding('utf8');
process.stdin.on('readable', process); // Set STDIN processing handler
但我收到以下错误:
process.stdin.setEncoding('utf8');
^
TypeError: Cannot read property 'setEncoding' of undefined
我根本无法理解它的原因,而且我在 Internet 上找不到任何关于此的信息。为什么我的 process.stdin 未定义?有什么想法吗?
您使用名为 process
的函数隐藏了 process
模块。
我相信你调试它的最佳尝试是 console.log(process)
并发现它看起来不像你期望的那样。