node.js process.stdout.write 类型错误

2023-12-19

我正在开发一个简单的函数来在 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 的支持别名 https://stackoverflow.com/questions/43362222/nodejs-shore-alias-for-process-stdout-write, 这 ”””this从别名调用时“””可能是未定义的。不过,我没有使用别名,而是直接调用“”“process.stdout.write”””。第一个实例,在“”“里面read()””” 函数工作正常,但作为回调的一部分的第二个实例却不能。更奇怪的是“”“console.log如果我在回调的第二个实例中替换它,“””就可以正常工作,尽管它应该只是“”“的包装器process.stdout.write“““ 功能。如何绑定“”“this””” 到字符串“”“output”“”或者,如果这不可行,我还能做些什么来解决错误“”“TypeError: Cannot read property '_writableState' of undefined”””?


When process.stdout.write()被调用,它期望绑定到process.stdout object.

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

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

此外,您的输入slice(0,-2)在 Linux 上不起作用(因为换行符只有一个字符 '\n' 而不是 Windows '\r\n') - 使用起来可能更容易input.toString().trim()或查找os.EOL一种与操作系统无关的方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

node.js process.stdout.write 类型错误 的相关文章

随机推荐