代码之家  ›  专栏  ›  技术社区  ›  Andrei

下一个.js:如果子进程没有要返回的任何数据,该怎么办?

  •  0
  • Andrei  · 技术社区  · 7 年前

    我在用下一个.js管道系统调用。代码看起来 有点像 这个(不是) 确切地

    export async function find(file, searchTerm) {
    
        const cat = execFile('cat', [file], {maxBuffer: 1024 * 1024});
        const grep = execFile('grep', [searchTerm], {maxBuffer: 1024 * 1024});
        cat.stdout.pipe(grep.stdin);
    
        return new Promise((resolve, reject) => {
            grep.stdout.on('data', async (d) => {
                setTimeout(() => resolve(d.toString().trim()), 100)
            });
        });
    }
    

    注意有两个过程:

    • cat

    • grep

    cat.stdout 被管道输送到 grep.stdin ,什么时候 grep.stdout 接收 data Promise .

    格雷普 不 找到 searchTerm 在返回的结果中 猫 grep.stdout.on('data', ... 没有被调用,整个链就挂起了。

    在生产中,我有一个抽象,它允许我将任意数量的过程链在一起(从 execFile 同上)。

    有没有一种方法可以检测链中的进程是否返回“nothing”,并沿着管道发送“nothing”(例如空字符串)?

    谢谢。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Mahendra suthar    7 年前

    您可以在此处使用“退出”事件。

    进程已退出,则code是进程的最终退出代码,否则 无效的。如果进程因接收到信号而终止,则信号为 始终为非空。

    所以你可以拒绝 承诺 发生此事件时。

    更多信息: https://nodejs.org/api/child_process.html#child_process_event_exit

        2
  •  1
  •   Ahm.    7 年前

    你可以打电话给 process.exit()

    const { execFile } = require('child_process');
    
    async function find(file, searchTerm) {
    
        const cat = execFile('cat', [file], {maxBuffer: 1024 * 1024});
        const grep = execFile('grep', [searchTerm], {maxBuffer: 1024 * 1024}, (error, stdout, stderr) => {
          //Because grep gives an empty string when no match
          if(stdout ===''){
            console.log('emptty')
            process.exit()
          }
        });
        cat.stdout.pipe(grep.stdin)
        return new Promise((resolve, reject) => {
            grep.stdout.on('data', async (d) => {
                setTimeout(() => resolve(d.toString().trim()), 100)
            });
        })
        .then(d => console.log('succes'))
    }
    
        3
  •  0
  •   Andrei    7 年前

    最后我做的是,对于链中的所有进程,我添加了以下事件侦听器:

    p.on('close', (code) => {
        if (code > 0) {
            reject(`child process PID ${p.pid} exited with code ${code}`);
        }
    });
    

    0 ( Promise .

    推荐文章