Skip to content

Instantly share code, notes, and snippets.

@shhider
Last active November 18, 2021 09:42
Show Gist options
  • Save shhider/353471d373966c04eb711044127309b7 to your computer and use it in GitHub Desktop.
Save shhider/353471d373966c04eb711044127309b7 to your computer and use it in GitHub Desktop.
[merge files by nodejs stream] #nodejs #stream #fs
async function mergeFiles(output, files) {
const outputStream = fs.createWriteStream(output, {
encoding: 'utf8',
flags: 'w+',
});
const merge = (fileToMerge) => new Promise((resolve, reject) => {
const fileStream = fs.createReadStream(fileToMerge, { encoding: 'utf8' });
fileStream.on('end', () => {
fileStream.close();
resolve(true);
}).on('error', (e) => {
reject(e);
});
fileStream.pipe(outputStream, { end: false });
});
for await (const file of files) {
await merge(file);
}
outputStream.close();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment