Last active
December 8, 2018 15:29
-
-
Save stephencweiss/e855feadc8468391ffa8230c656c23d9 to your computer and use it in GitHub Desktop.
Examples of using Node's fs to read a file from disk.
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
//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)} ) | |
} |
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
// 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