javascript - Node : short alias for process. stdout.write

标签 javascript node.js

我正在学习 nodejs(我喜欢它!)。我试图弄清楚如何为 console.log 设置更短的别名,我发现我可以使用 var cout=console.log 并使用 cout(' [string]') 从那时起。然后,当我想使用 process.stdout.write 时,我也尝试为它创建一个简短的别名,使用 var out=process.stdout.write。但是当我使用 out('[string]') 时,出现以下错误:

_stream_writable.js:220   var state = this._writableState;                   ^   TypeError: Cannot read property '_writableState' of undefined

    at Writable.write (_stream_writable.js:220:19)     at Socket.write (net.js:670:40)     at Object. (/home/shayan/Desktop/nodejs/server.js:12:1)

    at Module._compile (module.js:571:32)

    at Object.Module._extensions..js (module.js:580:10)     at Module.load (module.js:488:32)     at tryModuleLoad (module.js:447:12)     at Function.Module._load (module.js:439:3)     at Module.runMain (module.js:605:10)     at run (bootstrap_node.js:423:7)

这里有什么问题? 如何正确地为 process.stdout.write 创建一个简短的别名? 谢谢

最佳答案

你不应该做这种“短别名”。它非常困惑,阅读您的代码的人不会理解为什么您使用随机函数名称而不是 console.log。但是,如果您真的想创建函数别名,请考虑使用 function:

function out(text) {
    //    ^    ^- argument accepted by the function
    //    |------ the function name
    process.stdout.write(text)
    //                     ^- pass the argument you accepted in your new function to the long function
}

我添加了一些解释,以防您不知道某个函数的工作原理,您可以安全地删除它。

编辑: 它不起作用的原因在于 Node.JS 的源代码。您返回的堆栈跟踪指向 this行:

Writable.prototype.write = function(chunk, encoding, cb) {
    var state = this._writableState;
    // ...
}

它尝试从 this 引用一个名为 _writableState 的变量。如所写here :

Inside a function, the value of this depends on how the function is called.

这意味着,当您调用 process.stdout.write 时,this 指的是 process.stdout,但是它是未定义的,当您从你的别名中调用它。因此你会得到一个 Cannot read property '_writableState' of undefined 异常(因为 undefined 不包含那个变量,这对 write 函数很重要执行)。

关于javascript - Node : short alias for process. stdout.write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43362222/

相关文章:

javascript - KnockoutJS 不绑定(bind)数据

javascript - 为什么vue中的作用域样式没用?父元素样式仍然影响子元素

javascript - 使用 Jquery 将 iframe 调整为内容

javascript - 什么是||字符在 Javascript 中代表什么?实际上我将它与 Nodejs 和 Passport 一起使用

javascript - 为什么我不能在 node.js 中对这个 URL 进行 url 编码?

javascript - 尝试连接到 Stripe 时我的脚本不会执行

javascript - 如何使 Autobahn-JS 在 QML 中工作?

javascript - Node JS : File upload Error [ERR_STREAM_WRITE_AFTER_END]

javascript - jQuery 选择器性能 : by ID versus by tag with ID pattern

javascript - 从javascript中的数组中删除对象