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