javascript - Node.js 代码排序——是否有可能在监听器就位之前发出数据

标签 javascript node.js

此代码来自 Professional Node.js Building 基于 Javascript 的可扩展软件:

var spawn = require('child_process').spawn;

// Spawn the child with a node process executing the plus_one app
var child = spawn('node', ['06_plus_one.js']);

// Call this function every 1 second (1000 milliseconds):
setInterval(function() {

  // Create a random number smaller than 10.000
  var number = Math.floor(Math.random() * 10000);

  // Send that number to the child process:
  child.stdin.write(number + "\n");

  // Get the response from the child process and print it:
  child.stdout.on('data', function(data) {
    console.log('child replied to ' + number + ' with: ' + data);
  }); 
}, 1000);

child.stderr.on('data', function(data) {
  process.stdout.write(data);
});

子进程只是增加从父进程传递的数字。 child.stdin.write() 是否有可能转到子进程,并且在父进程注册其 data 监听器之前,子进程已经发出 data事件?

还有第二个问题。该代码最初的子程序文件名不正确,从而引发错误。如何捕获来自spawn的错误?

最佳答案

  • 警告,检测到内存泄漏!不要在循环内附加监听器 (setInterval)。每一秒你都在添加一个监听器。将此代码放在 setInterval 回调之外:

    child.stdout.on('data', function(data) {
        console.log('child replied to ' + number + ' with: ' + data);
    });
    
<小时/>
  • 子进程只是增加从父进程传递的数字。 child.stdin.write() 是否可能转到子进程,并且在父进程注册其数据监听器之前,子进程已经发出数据事件?

    没有。两个原因:

    • 阅读之前的评论。您必须将监听器附加到 setInterval() 之外,就像 stderr.on("data") 一样。
    • child 将在稍后的时间里发送消息。在当前循环中,您编写消息,在未来的循环中,您会收到子级的响应。这是 1 个线程异步性的定义(在 javascript 层)。
<小时/>
  • 还有第二个问题。该代码最初的子程序文件名不正确,从而引发错误。如何从生成中捕获错误?

    你尝试过 try catch spawn()函数吗?

关于javascript - Node.js 代码排序——是否有可能在监听器就位之前发出数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22707430/

相关文章:

node.js - Mongoose - 使用 findoneandupdate 和 $push 添加或更新子文档(当 upsert 为 true 时)

javascript - 包括调整大小事件的方向更改

javascript - 创建简单的游戏但 Canvas 上什么也没有显示

javascript - 在 ng-click AngularJS 上附加一个带有字符串的文本区域输入类型

javascript - 点击 Node.js 站点时偶尔出现 ERR_CONNECTION_RESET 错误

node.js - 将 'virtual' 变量添加到 Mongoose 模式?

node.js - Node JS Passport google oauth 无法在 https 上工作?

javascript - 对 JQuery 源的奇怪 RequireJS 调用

javascript - 如何在后端检测前端 Action ?

json - 无法通过声明的 mongoosejs 模式保存 JSON