I'm trying to get my head around generators and yield in JavaScript and Node.js, but having an issue.
Ideally, what I'd want to do is wrap fs.readFile with generators/yield, so that I can use it synchronously without blocking anything.
I've come up with the following code:
function readFileSync (path) {
return (function *(){
return yield require('fs').readFile(path, function *(err, data){
yield data;
});
})();
}
console.log(readFileSync('test-file.txt'));
But, unfortunately, readFileSync
just always returns {}
instead of the file content.
Hopefully what I want to achieve is still possible, or perhaps I've completely missed the point of generators/yield and I'm using it entirely incorrectly, in which case pointing out where I've gone wrong and any resources would be great.