Chris Rutherford
Chris Rutherford

Reputation: 1672

Fs.writeFile callback not called

Node version: 8.11.2

I have a simple CSV export function that takes an array of objects, and generates the headers of the file based on the object properties of the objects.

const exportCsv = (list, fileName) => {
  if (list.length > 0) {
    let headers = Object.keys(list[0]);
    let opts = { headers };
    let parser = new Parser(opts);
    let csv = parser.parse(list);
    fs.writeFile(`./output/${fileName}.csv`, csv, err => {
      if (err) {
        console.error(err);
      }
      console.log(`Wrote ${fileName} to disk.`);
    });
  } else {
    console.log('List is Empty. Nothing to export.');
  }
};

It was working great, but now the call back in the fs.writeFile call isn't firing, and there are no errors or exceptions from VS Code's Debugger.

What would cause it to nut run?

Upvotes: 1

Views: 1193

Answers (1)

bookotl
bookotl

Reputation: 68

If process is dead before the writing path is done, your callback will not be called because it is an asynchronous.

So you have 3 options

  1. make sure your process is not dead before writing path is done (you can use async/await or promise)
  2. use writeFileSync instead (less effective but less confusing)

Upvotes: 1

Related Questions