【发布时间】:2022-02-10 01:07:05
【问题描述】:
我想从不同的 CSV 文件中读取列,并将这些列组合成一个数组。我正在使用fs.readFile 读取CSV 文件和一个回调来处理数据并将一个新元素推送到列数组中。然后将此列数组发送到软件的另一部分(我正在构建一个电子应用程序,因此将其发送到渲染进程)。
我遇到的问题是“fs.readFile”是异步的,所以我的columns 数组在任何fs.readFile 调用完成之前被发送出去,导致一个空数组。
解决此问题的最佳方法是什么?就是简单的使用fs.readFileSync?有没有办法在不阻塞执行的情况下做到这一点?
下面的最小示例代码:
//Process each column, reading the file and extracting the data one at a time
let columns: (number[] | undefined)[] = []; //Somewhere to store the processed columns
for (const dataHandle of dataHandles)
{
//read the file as a raw string
fs.readFile(dataHandle.filePath, (error: any, data: any) => {
if (error) {
console.log("Error reading file:", error);
} else {
data = data.toString();
const newColumn = parseColumnFromStringDataframe(data, dataHandle.columnName);
columns.push(newColumn);
}
})
}
//Finished processing each column, so send response.
//BUT... readfile is non-blocking! Sends the response before anything is pushed to columns! How can we wait in a smart way?
console.log(columns); // []
mainWindow?.webContents.send("readDataProductColumnsResponse", columns); //Sends response
【问题讨论】:
标签: node.js typescript asynchronous electron fs