writestream 完成后如何返回承诺?

问题描述 投票:0回答:3

我有这样一个函数,它创建一个写入流,然后将字符串数组写入文件。我想让它在编写完成后返回一个 Promise。但我不知道如何才能完成这项工作。

function writeToFile(filePath: string, arr: string[]): Promise<boolean> {
   const file = fs.createWriteStream(filePath);
   arr.forEach(function(row) {
     file.write(row + "\n");
   });
   file.end();
   file.on("finish", ()=>{ /*do something to return a promise but I don't know how*/});
}

感谢您的任何评论!

javascript node.js typescript promise fs
3个回答
38
投票

您需要使用

Promise
构造函数:

function writeToFile(filePath: string, arr: string[]): Promise<boolean> {
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(filePath);
    for (const row of arr) {
      file.write(row + "\n");
    }
    file.end();
    file.on("finish", () => { resolve(true); }); // not sure why you want to pass a boolean
    file.on("error", reject); // don't forget this!
  });
}

3
投票

您需要在操作完成之前返回

Promise

比如:

function writeToFile(filePath: string, arr: string[]): Promise<boolean> {
    return new Promise((resolve, reject) => {
        const file = fs.createWriteStream(filePath);
        arr.forEach(function(row) {
            file.write(row + "\n");
        });
        file.end();
        file.on("finish", () => { resolve(true) });
    });
}

0
投票

在最新的 Node.js 版本中,您可以使用流包中的实用函数 finished,如下所示:

import { finished } from 'node:stream/promises';
import { createWriteStream } from 'node:fs';

function writeToFile(filePath: string, arr: string[]): Promise<boolean> {
  const file = createWriteStream(filePath);
  arr.forEach((row) => file.write(row + "\n"));
  file.end();
  return finished(file);
}
© www.soinside.com 2019 - 2024. All rights reserved.