Skip to content

Instantly share code, notes, and snippets.

@stephencweiss
Last active December 8, 2018 15:29
Show Gist options
  • Save stephencweiss/e855feadc8468391ffa8230c656c23d9 to your computer and use it in GitHub Desktop.
Save stephencweiss/e855feadc8468391ffa8230c656c23d9 to your computer and use it in GitHub Desktop.
Examples of using Node's fs to read a file from disk.
//NB: assumes encoding is 'utf8'; adjust as necessary
const readFromDiskAsync = (file) => {
fs.readFile(file, { encoding:'utf8'}, function read(err, data) {
if (err) {throw err;}
console.log('The data is --> ', data)
})
}
const readFromDiskStream = (file) => {
let newReadStream = fs.createReadStream(file, { encoding: 'utf8' })
let results = '';
newReadStream
.on('ready', console.log('ready to stream'))
.on('data', function processChunk(chunk) {
console.log('processing a chunk')
results += chunk;
})
.on('end', (results) => { console.log('The results are --> ', results)} )
}
// Instead of putting everything into the .on('end') event, use a Promise Chain
// NB: Only works if the logString is not *too* big to hold in memory.
// If that's *not* the case, make sure to be modifying the stream as needed during the .on('data') events.
const fs = require ('fs');
const path = require ('path');
const sampleInput = path.resolve(__dirname, './sample-input')
const readPuzzleInput = (file) => {
// I: A file with sample data
// O: An array of numbers
return new Promise ((resolve, reject) => {
let readStream = fs.createReadStream(file, {encoding:'utf8'});
readStream
.on('data', function processChunk(chunk) {
logString += chunk;
})
.on('end', () => {
logEntries = logString.split('\n')
resolve(logEntries)
})
})
};
Promise.resolve(readPuzzleInput(sampleInput))
.then(()=> console.log(logEntries))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment