Search code examples
javascriptc++node.jschild-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. Within this file I export the reference of the event emitter as I wish to use it in another file user.js. When I run the index.js everything works as expected. Then when I open another ternimal and run the user.js it writes to the console.log as expected. 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.

index.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

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

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

Solution

  • 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

    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

    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