0

code1

var fs = require("fs");
fs.readFile(process.argv[2],"utf8",function(err,data){
    if(err)throw err;
    console.log(data.split(/\n/).length-1);
});

code2

var fs = require("fs");
var str;
fs.readFile(process.argv[2],'utf8',function(err,data){
    if(err)throw err;
    str=data;
});
var arr = str.split(/\n/);
console.log(arr.length-1);

Hi everyone, I'm learning for node.js now, and above code is to read a file then count the number of its newlines asynchronously. For code1, it can work correctly, but for code2, str will get "undefined" value. I have no idea why it happened, does that mean I can not assign variable in the callback function? Or do I miss anything else? Thanks

NoelChiang
  • 13
  • 2

1 Answers1

1

The var arr = str.split(/\n/); is executed before the file is read. At this point str is still undefined. The callback is intended to be the code that executes after the async process is completed. This allows node to be responsive while (generally) only having a single thread.

Node also has a readFileSync method, but this generally defeats the purpose of using Node since your entire program will block while the file is read.

pherris
  • 17,195
  • 8
  • 42
  • 58