在node.js中对流使用promise

bprjcwpo  于 2023-08-04  发布在  Node.js
关注(0)|答案(5)|浏览(103)

我重构了一个简单的实用程序来使用promise。它从网络上获取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);
  })
}

字符串

eyh26e7m

eyh26e7m1#

在这一行

stream.on("end", resolve(stream.dests[0].path));

字符串
你正在立即执行resolve,调用resolveresult(它将是undefined的,因为这是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));
不,不要这样做:P查看评论

vxqlmq5t

vxqlmq5t2#

经过一系列的尝试,我找到了一个解决方案,它的工作一直很好。更多信息请参见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);
}

**更新。**我已经将上面的函数发布为Node模块:http://npm.im/promisified-pipe

ckocjqey

ckocjqey3#

流承诺API

v15新增的这个API提供了stream.finished

const { finished } = require('node:stream/promises');
const fs = require('node:fs');

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.

字符串
https://nodejs.org/api/stream.html#stream_event_finish

332nm8kg

332nm8kg4#

另一个解决方案可能看起来像这样:

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))

o2g1uqev

o2g1uqev5#

使用promised pipeline函数可以很好地做到这一点。管道还提供了额外的功能,比如清理流。

const pipeline = require('util').promisify(require( "stream" ).pipeline)

pipeline(
  request('http://somewebsite/some.pdf'),
  fs.createWriteStream('/local/some.pdf')
).then(()=>
  shell.exec('open /local/some.pdf').code !== 0)
);

字符串

相关问题