在 node.js 中对流使用 promise [英] Using promises with streams in node.js
问题描述
我重构了一个简单的实用程序来使用 promise.它从网上获取 pdf 并将其保存到磁盘.一旦保存到磁盘,它应该然后在 pdf 查看器中打开文件.该文件出现在磁盘上并且有效,shell 命令打开 OSX Preview 应用程序,但弹出一个对话框,抱怨该文件为空.
I've refactored a simple utility to use promises. It fetches a pdf from the web and saves it to disk. It should then open the file in a pdf viewer once saved to disk. The file appears on disk and is valid, the shell command opens the OSX Preview application, but a dialog pops up complaining that the file is empty.
将文件流写入磁盘后,执行 shell 函数的最佳方法是什么?
What's the best way to execute the shell function once the filestream has been written to disk?
// download a pdf and save to disk
// open pdf in osx preview for example
download_pdf()
.then(function(path) {
shell.exec('open ' + path).code !== 0);
});
function download_pdf() {
const path = '/local/some.pdf';
const url = 'http://somewebsite/some.pdf';
const stream = request(url);
const write = stream.pipe(fs.createWriteStream(path))
return streamToPromise(stream);
}
function streamToPromise(stream) {
return new Promise(function(resolve, reject) {
// resolve with location of saved file
stream.on("end", resolve(stream.dests[0].path));
stream.on("error", reject);
})
}
推荐答案
在这一行
stream.on("end", resolve(stream.dests[0].path));
您正在立即执行 resolve
,以及调用 resolve
的结果(这将是未定义的,因为这就是 resolve
返回)用作 stream.on
的参数 - 根本不是你想要的,对吧.
you are executing resolve
immediately, and the result of calling resolve
(which will be undefined, because that's what resolve
returns) is used as the argument to stream.on
- not what you want at all, right.
.on
的第二个参数需要是一个函数,而不是调用函数的结果
.on
's second argument needs to be a function, rather than the result of calling a function
因此,代码需要
stream.on("end", () => resolve(stream.dests[0].path));
或者,如果你是老派:
stream.on("end", function () { resolve(stream.dests[0].path); });
另一种老派的方式就像
another old school way would be something like
stream.on("end", resolve.bind(null, stream.dests[0].path));
不,不要那样做 :p 看评论
No, don't do that :p see comments
这篇关于在 node.js 中对流使用 promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!