为什么我得到process.stdin undefined

Pab*_*nda 2 javascript stdin node.js

我正在尝试用以下代码做一个简单的地图(唯一重要的部分是最后两行)

/**
 * 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
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

process.stdin.setEncoding('utf8');
         ^
TypeError: Cannot read property 'setEncoding' of undefined
Run Code Online (Sandbox Code Playgroud)

我根本无法理解它的原因,我在互联网上找不到任何关于此的内容.为什么我的process.stdin未定义?任何的想法?

dje*_*lin 7

process使用名为的函数隐藏了模块process.

我相信你最好的调试方法是console.log(process)看到它看起来不像你期望的那样.