一般来说,我会说这是一种合理的方法,但我在这里看到了一些问题:
- 块可能不包含您要查找的整个单词,但它可能介于两者之间(一个块
'sta'
以'rted'
.
- 在最初的发现之后,你仍然有一个你实际上不再需要的转换流
- 还有 unicode 字符的问题,但既然你正在寻找
' 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
}