readFile在其余代码执行之后读取我的文件



我希望我能深入了解一些情况。readFile在执行其余代码之后读取我的文件。我需要文件中的信息,以便在代码的其余部分中使用它。我一直在研究同步和异步,但我不知道它是如何应用的。

这是我的readfile代码,下面是依赖于该文件中数据的其他代码。

const carPartlist = () => {
const fs = require('fs');
fs.readFile("doc.csv", "utf8", (error, textContent) => {
if (error) {
throw error;
}
for (let row of textContent.split("n")) {
const rowItems = [row.split(",")];
console.log(rowItems);
}
})
}
carPartlist();

读取async是个好主意(以而不是在同步读取时阻止您的应用程序(。这样做。。。

const carPartlist = async () => {
const fs = require('fs').promises; // node >= 10
const textContent = await fs.readFile("doc.csv", "utf8");
for (let row of textContent.split("n")) {
const rowItems = [row.split(",")];
console.log(rowItems);
}
}
carPartlist();

EDIT也许我被误解了,因为我结束了OP结束的片段。完整的OP代码可能在carPartList之前和/或之后执行代码。之后必须完成的工作可以通过以下两种方式之一进行编码:

// at the top level
carPartlist().then(() => {
// code here that depends on carPartList being run
// presumably, the more complete OP code does something with the data it reads
})
// or, in a function
async functionThatRunsEarly() {
await carPartlist();
// code here that depends on carPartList being run
}

根据OP的问题(与一些评论相反(,这是进行文件i/o的正确方式,这不会阻塞应用程序的线程,这确实会导致";这里的代码依赖于carPartList";(以及该函数中的读取后代码(,以便在读取后执行。

最新更新