Skip to content

Instantly share code, notes, and snippets.

@dalaidunc
Last active January 5, 2019 11:44
Show Gist options
  • Save dalaidunc/a30c146bcf78a3aaffb0522639e39854 to your computer and use it in GitHub Desktop.
Save dalaidunc/a30c146bcf78a3aaffb0522639e39854 to your computer and use it in GitHub Desktop.
2 approaches to reading text files with node.js
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);
const readdir = util.promisify(fs.readdir);
async function read1 (file) {
const label = `read1-${file}`;
console.time(label);
const data = await readFile(file, 'utf8');
const header = data.split(/\n/)[0];
console.timeEnd(label);
}
async function read2 (file) {
return new Promise(resolve => {
let header;
const label = `read2-${file}`;
console.time(label);
const stream = fs.createReadStream(file, {encoding: 'utf8'});
stream.on('data', data => {
header = data.split(/\n/)[0];
stream.destroy();
});
stream.on('close', () => {
console.timeEnd(label);
resolve();
});
});
}
async function startTests(files) {
for (let file of files) {
console.log(file);
await read1(file);
await read2(file);
}
}
readdir(__dirname).then(files => {
startTests(files.filter(file => /dummy\d+\.csv/.test(file)));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment