我为process.stdin
编写了测试代码:
console.log('User input: ');
process.stdin.setEncoding('utf8');
process.stdin.on('readable', () => {
const chunk = process.stdin.read();
if (chunk) {
process.stdout.write('Print Data: ', chunk, '\n');
}
});
process.stdin.on('end', () => {
process.stdout.write('end.\n');
});
当我输入一些文字时,请按enter
,node.js
给我:
buffer.js:302
throw new TypeError('"encoding" must be a valid string encoding');
^
TypeError: "encoding" must be a valid string encoding
at fromString (buffer.js:302:13)
at Function.Buffer.from (buffer.js:173:12)
at createWriteReq (net.js:803:45)
at WriteStream.Socket._writeGeneric (net.js:754:11)
at WriteStream.Socket._write (net.js:777:8)
at doWrite (_stream_writable.js:385:12)
at writeOrBuffer (_stream_writable.js:371:5)
at WriteStream.Writable.write (_stream_writable.js:288:11)
at WriteStream.Socket.write (net.js:695:40)
at ReadStream.process.stdin.on (/Users/elsa/workspace/Training.nodejs/examples/api/process/stdin.js:7:20)
如何解决这个问题?感谢。
答案 0 :(得分:1)
问题在于:
process.stdout.write('Print Data: ', chunk, '\n');
您需要连接字符串。这不是console.log函数,例如:
process.stdout.write('Print Data: ' + chunk + '\n');