Fs dump equivalent in NodeJs?

purpose

Forcing fs (and the libraries using it) to write everything to files before the application terminates.

Background

I am writing an object to a CSV file using the npm package csv-write-stream .

As soon as the library finishes writing the CSV file, I want to complete my application using process.exit().

the code

To achieve the above goal, I wrote the following:

let writer = csvWriter({
  headers: ['country', 'postalCode']
});

writer.pipe(fs.createWriteStream('myOutputFile.csv'));

//Very big array with a lot of postal code info
let currCountryCodes = [{country: Portugal, postalCode: '2950-286'}, {country: Barcelona, postalCode: '08013'}];

for (let j = 0; j < currCountryCodes.length; j++) {
  writer.write(currCountryCodes[j]);
}

writer.end(function() {
  console.log('=== CSV written successfully, stopping application ===');
  process.exit();
});

Problem

The problem is that if I execute process.exit(), the library will not have time to write to the file and the file will be empty.

Since the library uses fs, my solution to this problem is to force fs.dump()or something similar in NodeJs, but after searching I did not find anything.

Questions

  • fs () ?
  • , , , ?
+4
1

, . process.exit(), .

, .

let r = fs.createWriteStream('myOutputFile.csv');
writer.pipe(r);

...

writer.end(function() {
  r.end(function() {
    console.log('=== CSV written successfully, stopping application ===');
    process.exit();
  });
});
+1

Source: https://habr.com/ru/post/1650554/


All Articles