Last active
January 5, 2019 11:44
-
-
Save dalaidunc/a30c146bcf78a3aaffb0522639e39854 to your computer and use it in GitHub Desktop.
2 approaches to reading text files with node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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