简体   繁体   English

Node.js:如何使 spawn function 同步而不是使用 spawnSync?

[英]Node.js : How to make spawn function synchronous instead of using spawnSync?

I'm currently using spawnSync and stdio:inherit to get the logs printed on my console.我目前正在使用 spawnSync 和 stdio:inherit 将日志打印在我的控制台上。 However I'm looking for custom logging to a separate file, in case if anything fails during the spawn.但是,我正在寻找自定义日志记录到一个单独的文件,以防在生成过程中出现任何故障。

I'm looking to create a wrapper around我正在寻找一个包装器

spawn产卵

so that it has following properties:使其具有以下性质:

  • Synchronous function where output is stored in a variable同步 function 其中 output 存储在变量中
  • View output on the console在控制台查看 output
  • Write stdout and stderr to a file将 stdout 和 stderr 写入文件

For instance:例如:

const result = spawnSync('ls', [ '-l', '-a' ], { stdio: 'inherit'}); // will print as it's processing
console.log(result.stdout); // will print null

const result = spawnSync('ls', [ '-l', '-a' ], { encoding: 'utf-8' }); // won't print anything
console.log(result.stdout); // will print ls results only on completion

I need result such that it will print while it's processing and write to a file at the same time我需要result ,以便它在处理时打印并同时写入文件

Also I'm looking for some strategy or solution from node.js side apart from shell scripting除了 shell 脚本之外,我还在寻找 node.js 方面的一些策略或解决方案

I guess we can't make all three possible because of the limitation of node.js我想由于 node.js 的限制,我们无法使这三个都成为可能

As per the documentation根据文档在此处输入图像描述

If we are trying to use stdio:'inherit', we can either redirect output to parent stdout stream or file using如果我们尝试使用 stdio:'inherit',我们可以将 output 重定向到父 stdout stream 或使用文件

fs.openSync() fs.openSync()

Because of the limitation, we can't use custom streams too.由于限制,我们也不能使用自定义流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM