// Start of program4 processvar fs = require('fs');
// Asyncronously read and send the buffer object of a file whose path// is set int 2nd argument of the process to the callback function.var buffer = 0;fs.readFile(process.argv[2], fileReadCallBack);
while(buffer == 0) {}
var numOfNewLines = buffer.toString().split('\n').length-1;console.log(numOfNewLines);
// Our callback function for our asyncronous file readingfunction fileReadCallBack(err, data) { if(!err){ buffer = data; } }// Start of program4 processvar fs = require('fs');// Asyncronously read and send the buffer object of a file whose path// is set int 2nd argument of the process to the callback function.var buffer = 0;fs.readFile(process.argv[2], fileReadCallBack);while(buffer == 0) {}
var numOfNewLines = buffer.toString().split('\n').length-1;console.log(numOfNewLines);// Our callback function for our asyncronous file readingfunction fileReadCallBack(err, data) { if(!err){ buffer = data; } }
I'm using NodeSchool.io's workshop to learn Nodejs. I'm on problem 4, Async File I/O and the above code runs forever. If the file reading is asynchronous, I'm thinking var buffer should no longer be 0 and the while-loop will terminate and move on.
I know the correct solution would place the logic inside of the callback function, but I'm curious as to why the code above doesn't work as expected.
Thanks!
var buffer = 0;console.log('outside setTimeout');setTimeout(function () {console.log('inside setTimeout');buffer = 1;}, 10);console.log('before while');while(buffer == 0) {}console.log('after while');
--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/635a38d4-4f7c-402c-b841-7b682814143e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
console.log(data);
});
Hope this helps!