繁体   English   中英

node.js process.stdout.write TypeError

[英]node.js process.stdout.write TypeError

我正在使用一个简单的函数在node.js中创建基于控制台的提示,而无需使用大量额外的库:

“”“

function prompt(text, callback) { // Text can be a question or statement.
    'use strict';
    var input, output;

    process.stdout.write(text + ' ');
    process.stdin.addListener('readable', function read() { // Stream type *must* be correct!
        input = process.stdin.read();
        if (input) { // Wait for actual input!
            output = input.toString().slice(0, -2); // Slicing removes the trailing newline, an artifact of the 'readable' stream type.
            process.stdout.write('You typed: ' + output);
            process.stdin.pause(); // Stops waiting for user input, else the listener keeps firing.
            callback(output);
        }
    });
}

prompt('Enter some text:', process.stdout.write);
// Enter some text: x
// You typed: x_stream_writable.js:200
//   var state = this.writableState;
//
// TypeError: Cannot read property '_writableState' of undefined
//     ...

”””

按照问题nodejs:process.stdout.write的海岸别名,当从别名调用“”“ this ””时可以是未定义的。 但是,我没有使用别名,而是直接调用“”“ process.stdout.write ”””。 第一个实例在“”“ read() ””函数内部,可以正常工作,但第二个实例(作为回调的一部分)则不能。 甚至更奇怪的是,即使我在回调的第二个实例中替换“” console.log ”””,也可以正常工作,尽管据说它只是“” process.stdout.write ””函数的包装。 如何将““ this ””绑定到字符串““ output ””,或者,如果那不可行,我该怎么办才能解决错误“”? TypeError: Cannot read property '_writableState' of undefined “””?

调用process.stdout.write() ,它希望绑定到process.stdout对象。

您可以简单地绑定作为回调传递的函数:

prompt('Enter some text:', process.stdout.write.bind(process.stdout));

另外,您的输入slice(0,-2)在Linux上不起作用(因为换行符只是一个字符'\\ n'而不是Windows'\\ r \\ n')-仅使用input.toString().trim()或查找os.EOL ,以了解与操作系统无关的更多方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM