Im hoping I colould get some insite. The readFile reads my file after the rest of the code executes. I need the information from the file in order to use it within the rest of the code. I have been doing research on synchronous and asynchronous but I cant figure out how it applies.
This is my readfile code and below it other code begins that is dependent on the data within this file.
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();
It's a good idea to read async (to not block your app on a synchronous read). Do it like this...
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 maybe I'm being misunderstood because I ended the snippet where the OP's ended. The complete OP code probably executes code before and/or after carPartList. Work that must be done after can be coded one of two ways:
// 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
}
Per the OP's question (and contrary to some of the comments), this is the right way to do file i/o, this does not block the app's thread, this and does cause the "code here that depends on carPartList" (and the post-reading code in that function) to execute after the read.