首页 > 解决方案 > JS Promise 和 Pipe 的问题

问题描述

我正在尝试创建一个文件然后压缩它。但是,正在创建文件,但压缩的文件是空的。我确定我的 Promise 做错了什么,但我不确定它是什么,有什么想法吗?

const fs = require('fs')
const zlib = require('zlib');
const CSV = require("csv-parser");
const CSVOut = require("fast-csv");

async function processFeed() {
  let originalFile = await readFile();
  let manipulatedFile = processFeed2(originalFile);
  console.log('manipulatedFile ', manipulatedFile);
  await manipulatedFile.then(data => {
    console.log('here');
    const writeStream = fs.createWriteStream(`${__dirname}/myexcel.csv`);
      CSVOut.write(data, {headers: true}).pipe(writeStream).on('finished', () => {
        console.log('finished writing');
      });
  }).then(() => {
    console.log('now here');
    const readStream = fs.createReadStream(`${__dirname}/myexcel.csv`);
    const writeStreamFinal = fs.createWriteStream(`${__dirname}/myexcel.csv.gz`);
    const zip = zlib.createGzip();
    readStream.pipe(zip).pipe(writeStreamFinal);
    // fs.unlinkSync(`${__dirname}/myexcel.csv`);
    console.log('Total Count ' + totalCount);
    console.log('Removed Row Count ' + removedCount);
  });
}

标签: javascriptes6-promise

解决方案


使用 Promises 并then不会神奇地让代码等待流完成。您需要将您的流包装成一个承诺,当流发出finished事件时解决。

async function processFeed() {
  let originalFile = await readFile();
  let manipulatedFile = processFeed2(originalFile);
  console.log('manipulatedFile ', manipulatedFile);
  await manipulatedFile.then(data => {
    console.log('here');
    const writeStream = fs.createWriteStream(`${__dirname}/myexcel.csv`);
    
    // wrap the stream into a promise
    return new Promise((resolve, reject) => {
      CSVOut.write(data, {headers: true}).pipe(writeStream).on('finished', () => {
        console.log('finished writing');
        
        resolve(); // resolve the promise when the stream finished
      }).on('error',reject);
    })
  }).then(() => {
    console.log('now here');
    const readStream = fs.createReadStream(`${__dirname}/myexcel.csv`);
    const writeStreamFinal = fs.createWriteStream(`${__dirname}/myexcel.csv.gz`);
    const zip = zlib.createGzip();
    
    // wrap the stream into a promise
    return new Promise((resolve, reject) => {
      readStream.pipe(zip).pipe(writeStreamFinal).on('finished', () => {
        // fs.unlinkSync(`${__dirname}/myexcel.csv`);

        console.log('Total Count ' + totalCount);
        console.log('Removed Row Count ' + removedCount);
        resolve();  // resolve the promise when the stream finished
      }).on('error',reject)
    })
  });
}

您还应该处理流(监听error)事件的错误情况并reject在这种情况下调用。


推荐阅读