Skip to content

Instantly share code, notes, and snippets.

@gaurang847
Last active October 27, 2019 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaurang847/2309015f37f289f48d9adb3fccce7cd5 to your computer and use it in GitHub Desktop.
Save gaurang847/2309015f37f289f48d9adb3fccce7cd5 to your computer and use it in GitHub Desktop.
const fs = require("fs");
// this is the higher-order function that takes a callback function and passes it as an event-handler for concerned events
function readFile(filename, callback) {
let data = '';
let readStream = fs.createReadStream(filename, { encoding: 'UTF8' });
readStream.on('data', function (chunk) {
data += chunk;
});
readStream.on('end', function(){
callback(null, data)
});
readStream.on('error', function(err) {
callback(err)
});
}
readFile('input.txt', function(err, data){
// this is the function that is being passed to readFile as a callback.
// It prints the contents of 'input.txt' once it has been read
if(err)
console.log(err.stack);
// Or, in case an error occurs, it prints the error
else
console.log(data);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment