简体   繁体   English

使用 child_process 执行节点脚本

[英]Executing a node script with child_process

I have a simple node index.js file that uses an event emitter to emit data every two seconds.我有一个简单的节点index.js文件,它使用事件发射器每两秒发出一次数据。 Within this file I export the reference of the event emitter as I wish to use it in another file user.js .在这个文件中,我导出了事件发射器的引用,因为我希望在另一个文件user.js使用它。 When I run the index.js everything works as expected.当我运行 index.js 时,一切都按预期工作。 Then when I open another ternimal and run the user.js it writes to the console.log as expected.然后,当我打开另一个终端并运行 user.js 时,它会按预期写入 console.log。 What I would like to do is once I emit this event is create a new process that will run the user.js file and read its output to the current terminal instead of having to use separate terminals to get the result.我想要做的是,一旦我发出此事件,就创建一个新进程,该进程将运行 user.js 文件并将其输出读取到当前终端,而不必使用单独的终端来获取结果。

index.js索引.js

const { EventEmitter } = require('events');
const { spawnSync, spawn } = require('child_process');

const user = { id: 1, name: 'John Doe'}

const myEvent = new EventEmitter();
setInterval(() => {
    myEvent.emit('save-user', user);
}, 2000);
;
exports.emitter = myEvent;

user.js用户.js

const newEvent = require('./index')
const userEmitter = newEvent.emitter;

userEmitter.on('save-user', (user) => {
    console.log('Saving user data', user);
})

Here is a slightly different approach: you can run the user.js as the parent and have index.js on a child process.这是一种稍微不同的方法:您可以将 user.js 作为父进程运行,并在子进程上运行 index.js。

User.js用户.js

const newEvent = require("./index");
const { spawn } = require("child_process");

const userEmitter = newEvent.emitter;

userEmitter.on("save-user", (user) => {
  console.log("Saving user data", user);
});

spawn("node", ["./index.js"]);

index.js索引.js

const { EventEmitter } = require("events");

const user = { id: 1, name: "John Doe" };

const myEvent = new EventEmitter();
setInterval(() => {
  myEvent.emit("save-user", user);
}, 2000);

exports.emitter = myEvent;

Then run node user.js然后运行node user.js

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

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