I have this utility function which launches a child process. As soon as the child process writes a certain message to stdout, we are supposed to stop listening and fire the callback:
export const launchBrokerInChildProcess = function (opts: any, cb: Function) {
const host = opts.host || 'localhost';
const port = opts.port || 8019;
const detached = Boolean(opts.detached);
ping.probe(host, port, function (err, available) {
if (err) {
return cb(err)
}
if (available) {
log.info(`live-mutex broker/server was already live at ${host}:${port}.`);
return cb(null, {host, port, alreadyRunning: true});
}
log.info(`live-mutex is launching new broker at '${host}:${port}'.`);
const n = cp.spawn('node', [p], {
detached,
env: Object.assign({}, process.env, {
LIVE_MUTEX_PORT: port
})
});
if (detached) {
n.unref();
}
process.once('exit', function () {
if (!detached) {
n.kill('SIGINT');
}
});
n.stderr.setEncoding('utf8');
n.stdout.setEncoding('utf8');
n.stderr.pipe(process.stderr);
let stdout = '';
n.stdout.on('data', function (d) {
stdout += String(d);
if (stdout.match(/live-mutex broker is listening/i)) {
n.stdout.removeAllListeners();
if (detached) {
n.unref();
}
console.log(33333);
cb(null, {
liveMutexProcess: n,
host,
port,
detached
});
}
});
});
};
what's happening is that console.log(33333);
is being hit over and over and over again. Very strange - does anyone know why that would happen?
The ping.probe() callback is firing only once, I have confirmed that. So I don't know what's happening.
here is the script that gets launched:
import {Broker} from './broker';
const port = parseInt(process.argv[2] || process.env.LIVE_MUTEX_PORT || '6970');
new Broker({port: port}).ensure().then(function () {
console.log(`live-mutex broker is listening on port ${port}.`);
})
.catch(function (err) {
console.error(err.stack || err);
});
so that line ('live-mutex broker is listening') should only be logged once, given that it's a promise.
答案 0 :(得分:1)
也许其他人使用端口8019
,尝试使用其他端口,如3000
。