Reputation: 7047
I would to write a simple NodeJS app, that reads a file, analyzes its lines one-by-one and writes the result. Here is the code sample that works
var lines;
var fs = require('fs');
var data="";
fs.readFile('list.csv', 'ascii', function(err,data){
if(err) {
console.error("Could not open file: %s", err);
process.exit(1);
}
var data2=data.split(/[\n\r]+/);
for(var i=0; i<data2.length; i++){
/*LISTING ALL THE LIST LINE-BY-LINE */
console.log(i + data2[i]);
}
});
I'd like to know why I should write my code inside function(err,data){..*my-code*..}
? I tried to declare all the variables as global and write
console.log();
at the end of the code – it seems it just dosen't execute this code line. So, why cant I write my code outside function(err,data){}
?
Upvotes: 0
Views: 133
Reputation: 4368
By default all file system operations are non-blocking, so the result needs to be used in a callback function that runs when the operation completes, in this case when the file has finished being read into a variable.
While it's generally a better design to use non-blocking IO to allow the server to run multiple operations at the same time, you can switch most of the fs
operations to run synchronously:
var data = fs.readFileSync('list.csv', 'ascii');
Upvotes: 0
Reputation: 2912
If you should need a "blocking behavior" you can use the synchronous fs methods.
Please see the documentation:
http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_encoding
Upvotes: 0
Reputation: 28795
One of the main features of NodeJS is the non-blocking event loop. When functions take a long time, the Node script doesn't wait for the function to return, which is why you need to pass in your code in a callback.
Upvotes: 1