我的程序接收CSV文件,并尝试将它们合并为一个CSV文件。所有CSV文件将具有相同的列。
我正在使用fast-csv包来解析和格式化CSV文件的行,但是我很难将它们全部连续地放入一个文件中。
我正在遍历文件并运行解析和格式化行的函数,但是输出文件无序,并且不包含文件中的所有数据。
我认为这是由于我用于遍历不同CSV文件参数的“ for”循环的同步特性,以及从不同流读取并尝试写入单个流的异步特性。
>我正在寻找一些有关如何循环遍历每个文件参数的指南,但是在继续下一个文件之前-该文件的解析,格式化和写入输出文件已完成。
// Function that parses and formats the given file
function formatFile(paths, index) {
// Initialize format options
let formatOptions = {
quoteHeaders: true,
quoteColumns: true,
escape: '\\'
};
// If the current file is the first file, write the headers of the file
if (index === 0) {
formatOptions.headers = true;
// If the current file is not the first file, do not write the headers of the file
} else {
formatOptions.writeHeaders = false;
}
// Take in the current file as a readable stream
fs.createReadStream(paths[index])
// Parse the CSV file
.pipe(csv.parse({ headers: true, escape: '\\' }))
// Format the rows of the CSV file
.pipe(csv.format(formatOptions))
// Pipe the formatted data into the output CSV file
.pipe(outputFile);
}
// Loop through each CSV file argument and run the formatFile function on each
for (let i = 0; i < filePaths.length; i++) {
formatFile(filePaths, i);
}
答案 0 :(得分:1)
使用承诺。
// Function that parses and formats the given file
function formatFile(paths, index) {
// Initialize format options
let formatOptions = {
quoteHeaders: true,
quoteColumns: true,
escape: '\\'
};
// If the current file is the first file, write the headers of the file
if (index === 0) {
formatOptions.headers = true;
// If the current file is not the first file, do not write the headers of the file
} else {
formatOptions.writeHeaders = false;
}
// Take in the current file as a readable stream
const stream = fs.createReadStream(paths[index])
// Parse the CSV file
.pipe(csv.parse({ headers: true, escape: '\\' }))
// Format the rows of the CSV file
.pipe(csv.format(formatOptions))
// Pipe the formatted data into the output CSV file
.pipe(outputFile);
return new Promise(resolve => stream.on('finish', resolve))
}
// Loop through each CSV file argument and run the formatFile function on each
for (let i = 0; i < filePaths.length; i++) {
await formatFile(filePaths, i);
}
包含for循环的函数必须是异步函数。