我重构了一个使用promises的简单实用程序.它从Web获取pdf并将其保存到磁盘.然后它应该保存到磁盘后在pdf查看器中打开文件.该文件出现在磁盘上并且有效,shell命令打开OSX预览应用程序,但会弹出一个对话框,抱怨该文件为空.
将文件流写入磁盘后,执行shell函数的最佳方法是什么?
// 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);
})
}
Run Code Online (Sandbox Code Playgroud)