Home > Software design >  How to return ChildProcess of spawn to other file?
How to return ChildProcess of spawn to other file?

Time:08-06

I have uses case like run a process. i need to seperate implementation when to call exit code for this process in other file. ex, application run ping process. in specific event from application can kill process.

the problem is cant return ping instance. undefined.

ping.js

const { spawn } = require('child_process');

class Ping {
    flags:  string[];

    constructor(flags: string[]) {
        this.flags = [...flags]
    }

    run() {
        const ping = spawn('ping', this.flags);

        ping.on('spawn', () => {
            return ping
        })
    }
}

export = Ping

application.js

const Ping = require('ping.js');

const duration = 5000;
const end_time = Date.now()   duration;
const flags = ['-t', 'stackoverflow.com'];
const ping = new Ping(flags)
const pingProcess = ping.run();

pingProcess.stdout.on('data', chunk => {
    console.log(chunk.toString())
})

while(true) {
  const current_time = Date.now();

  if (current_time > end_time) {
    pingProcess.kill()
    break;
  }
}

CodePudding user response:

You can return the child process right after spawning it:

class Ping {
    flags:  string[];

    constructor(flags: string[]) {
        this.flags = [...flags]
    }

    run() {
        const ping = spawn('ping', this.flags);

        ping.on('error', () => {
            /* error handling logic */
        })

        return ping
    }
}
  • Related