因此,我正在使用Node的child_process
模块来生成弹性搜索的实例。我需要检查服务何时启动,resolve()
承诺何时启动。这就是我现在正在做的事情:
const { join } = require('path');
const { spawn } = require('child_process');
const { createWriteStream } = require('fs');
const { Transform } = require('stream');
function start() {
return new Promise(resolve => {
const outStream = new Transform({
transform(chunk, encoding, callback) {
if (chunk.toString().includes('started')) resolve();
this.push(chunk);
callback();
}
});
const logFile = createWriteStream(join(LOG_DIR, 'es.log'), 'w');
const errorFile = createWriteStream(join(LOG_DIR, 'es.error.log'), 'w');
outStream.pipe(logFile);
child = spawn(
ES_BAT_PATH,
[],
{ cwd: process.cwd(), stdio: ['ignore', outStream, errorFile] }
);
});
}
这是最好的方法吗? (可能不是),如果没有,我该怎么做?
答案 0 :(得分:0)
总的来说,我会说这是一种合理的方法,但是我在这里看到了一些问题:
'sta'
结尾,下一个以'rted'
开头。' started '
,因此可以省略。通过将最后一部分保留在空格后,可以轻松缓解第一个问题。对于第二个,您需要解压转换-这样您将得到如下结果:
const { join } = require('path');
const { spawn } = require('child_process');
const { createWriteStream } = require('fs');
const { Readable, PassThrough } = require('stream');
function start() {
return new Promise(resolve => {
const outStream = new PassThrough();
let last;
const lookupStream = new Readable({
read(chunk, encoding, callback) {
const ref = chunk.toString();
if ((last + ref).includes('started')) {
outStream.unpipe(lookupStream);
resolve();
}
last = ref.replace(/^.* /, '');
callback();
}
});
const logFile = createWriteStream(join(LOG_DIR, 'es.log'), 'w');
const errorFile = createWriteStream(join(LOG_DIR, 'es.error.log'), 'w');
outStream.pipe(logFile);
outStream.pipe(lookupStream);
child = spawn(
ES_BAT_PATH,
[],
{ cwd: process.cwd(), stdio: ['ignore', outStream, errorFile] }
);
});
}
另一种选择是使用on('data'
侦听器,并在找到正确的块后将其删除。
最后,我的框架scramjet
会让这变得容易一些
const { join } = require('path');
const { spawn } = require('child_process');
const { createWriteStream } = require('fs');
const { StringStream } = require('scramjet');
function start() {
const outStream = new PassThrough();
const lookupStream = new StringStream();
const logFile = createWriteStream(join(LOG_DIR, 'es.log'), 'w');
const errorFile = createWriteStream(join(LOG_DIR, 'es.error.log'), 'w');
outStream.pipe(logFile);
outStream.pipe(lookupStream);
child = spawn(
ES_BAT_PATH,
[],
{ cwd: process.cwd(), stdio: ['ignore', outStream, errorFile] }
);
return lookupStream
.split('\n') // split line by line
.filter(x => x.includes('started')) // check if line contains "started"
.until(x => outStream.unpipe(lookupStream)) // end stream on first occurence
.run(); // run and resolve on stream end
}