-
-
Save gaurang847/2309015f37f289f48d9adb3fccce7cd5 to your computer and use it in GitHub Desktop.
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"); | |
// 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