我重构了一个使用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);
})
}
答案 0 :(得分:10)
在这一行
stream.on("end", resolve(stream.dests[0].path));
您正在立即执行resolve
,以及调用resolve
的结果(这将是未定义的,因为resolve
返回的是stream.on
被用作.on
的参数 - 不是你想要的,对吧。
stream.on("end", () => resolve(stream.dests[0].path));
的第二个参数需要是函数,而不是调用函数的结果
因此,代码需要
stream.on("end", function () { resolve(stream.dests[0].path); });
或者,如果你是老学校:
stream.on("end", resolve.bind(null, stream.dests[0].path));
另一种老派的方式就像
dns
不,不要这样做:p见评论
答案 1 :(得分:5)
经过一系列的尝试,我找到了一个解决方案,它始终正常工作。有关详细信息,请参阅JSDoc注释。
/**
* Streams input to output and resolves only after stream has successfully ended.
* Closes the output stream in success and error cases.
* @param input {stream.Readable} Read from
* @param output {stream.Writable} Write to
* @return Promise Resolves only after the output stream is "end"ed or "finish"ed.
*/
function promisifiedPipe(input, output) {
let ended = false;
function end() {
if (!ended) {
ended = true;
output.close && output.close();
input.close && input.close();
return true;
}
}
return new Promise((resolve, reject) => {
input.pipe(output);
input.on('error', errorEnding);
function niceEnding() {
if (end()) resolve();
}
function errorEnding(error) {
if (end()) reject(error);
}
output.on('finish', niceEnding);
output.on('end', niceEnding);
output.on('error', errorEnding);
});
};
用法示例:
function downloadFile(req, res, next) {
promisifiedPipe(fs.createReadStream(req.params.file), res).catch(next);
}
答案 2 :(得分:1)
其他解决方案如下所示:
const streamAsPromise = (readable) => {
const result = []
const w = new Writable({
write(chunk, encoding, callback) {·
result.push(chunk)
callback()
}
})
readable.pipe(w)
return new Promise((resolve, reject) => {
w.on('finish', resolve)
w.on('error', reject)
}).then(() => result.join(''))
}
,您可以像这样使用它:
streamAsPromise(fs.createReadStream('secrets')).then(() => console.log(res))
答案 3 :(得分:0)
在最新的nodejs(特别是流v3)中,您可以这样做:
const finished = util.promisify(stream.finished);
const rs = fs.createReadStream('archive.tar');
async function run() {
await finished(rs);
console.log('Stream is done reading.');
}
run().catch(console.error);
rs.resume(); // Drain the stream.