如何将promisify()与spawn()函数一起使用the child_process的spawn()函数?
我有以下代码示例,现在我有关于如何使用 utils.promisify();
仅使用 utils.promisify();
!不承诺!
const spawn = child_process.spawn('docker', ['--version']);
spawn.stdout.on('data', (data) => {
process.stdout.write(data);
});
spawn.on('error', () => {
process.stderr.write(error);
process.exit(1);
});
第二个代码示例正常工作。
const promisifiedExecFile = promisify(child_process.execFile);
async function test() {
const version = await promisifiedExecFile('docker', ['--version']);
console.log(version);
}
test();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我无法快速找出为什么
Promisify
函数与Spawn
函数无法正常工作。但是您可以这样创建自己的尊贵功能:ts
js
I couldn't quickly find out why the
promisify
function does not work properly with thespawn
function. But you can create your own promisify function like this:TS
JS
Node.js的内置UTIL软件包具有
Promisify()
函数,可将基于回调的函数转换为基于承诺的函数。这使您可以使用基于回调的API使用承诺链式和异步/等待。我认为我们不能将
promisify()
与spawn()
函数一起使用。例如,我们可以将
Promisify()
与execfile()
而不是spawn()
::Node.js' built-in util package has a
promisify()
function that converts callback-based functions to promise-based functions. This lets you use promise chaining and async/await with callback-based APIs.I think that we can't use the
promisify()
with thespawn()
function.For example we can use
promisify()
withexecFile()
instead ofspawn()
:这是不可能的,因为没有什么可以
prosisify
。prosisify
在函数上工作,在该功能上进行回调,而spawn
不接听回调。您使用
Spawn
通过取返回的childprocess
然后将侦听器添加到childprocess
'可读流(stdout
,stderr ,
stdio
...)Omar Omeiri的答案与如何
execfile >,因此您可以改用Promisified
execfile
。 (如果您需要无限的缓冲区,请传递MaxBuffer:Infinity
内部选项)It is not possible because there is nothing to
promisify
.promisify
works on functions where it takes a callback andspawn
does not take a callback.You use
spawn
by taking the returnedChildProcess
then adding listeners to theChildProcess
' readable streams (stdout
,stderr
,stdio
...)Omar Omeiri's answer is similar to how
execFile
works inside node itself, so you can just use the promisifiedexecFile
instead. (if you need unlimited buffer, pass inmaxBuffer: Infinity
inside options)