Skip to content

Instantly share code, notes, and snippets.

@dudeuter
Last active February 3, 2023 01:32
Show Gist options
  • Save dudeuter/b2799d603364a670b8926689685d7014 to your computer and use it in GitHub Desktop.
Save dudeuter/b2799d603364a670b8926689685d7014 to your computer and use it in GitHub Desktop.
writing files node.js
const fs = require('fs');
const options = { encoding: 'utf-8' };
const writeStream = fs.createWriteStream('out2.txt', options);
const buffers = [];
let handled = 0;
function handler(error, buffer) {
if (error) {
console.error(error);
return;
}
handled += 1;
fs.writeFile('out1.txt', buffer, options, () => {
console.log('wrote to out1.txt');
});
writeStream.write(buffer, () => {
console.log('wrote to out2.txt\'s write stream');
});
buffers.push(buffer);
if (handled === 2) {
writeStream.close(() => {
console.log('closed file');
});
fs.writeFile('out3.txt', buffers.join(''), options, () => {
console.log('wrote to out3.txt');
});
}
}
fs.readFile('test1.txt', options, handler);
fs.readFile('test2.txt', options, handler);
Hello World
Hello World
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment