javascript - 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);
});
}
解决方案
使用 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
在这种情况下调用。
推荐阅读
- asp.net-mvc - 我可以在 .net core 3.0 上使用 Microsoft.AspNet.Identity
- javascript - 将 php 变量回显到 javascript 不起作用
- java - 使复活节计算器代码更有效的可能方法?
- gcc - 在 Sierra 上使用 g++ MacOS 的 OpenMP
- javascript - 如何从数据库中获取值并在 javascript 的选择选项中显示它们
- r - 如何克服 R 中的 t.test 错误,因为已经尝试过数字?
- php - 从数据库 codeigniter 获取选项值
- c++ - 有没有办法仅将 fnmatch 的 FNM_PATHNAME 标志应用于斜杠的第一个实例?
- python-2.7 - 从 csv 文件读取和写入:只想提取不包含零的行
- javascript - 关于带按钮的模板字符串循环的建议