Monday, July 1, 2013

Read a file line by line in node.js

Hi all. Today I decided to add a small functionality to my project: when I start my framework, I run stuff one after the other with a list of commands; I decided to add a functionality that reads a particular file (which I want to be a .k file) and extract the commands from that list.
To do so I need some things:

  1. Read a file
  2. Make sure it's a .k file
  3. Split it line by line
  4. Execute each line
Reading a file in node.js is very simple. We just need to import the fs module and call the function readFile:

fs.readFile(cmd[1], 'utf8', function(err, data) {
    if (err) throw err;
    //do something with the file
});

This will read the file specified in cmd[1] (which is the input variable I give). Next, I would like to add some more checks (for example, that it needs to be a .k file):
if(cmd[1].indexOf(".k") === cmd[1].length - 2){
    fs.readFile(cmd[1], 'utf8', function(err, data) {
 if (err) throw err;
 //do something with the file    
    });
}
else{
    console.log("Not a .k file!");
}

Finally, let's read the file line by line:
if(cmd[1].indexOf(".k") === cmd[1].length - 2){
    fs.readFile(cmd[1], 'utf8', function(err, data) {
 if (err) throw err;
 
 var commands = data.split('\n');
 for(var i = 0; i < commands.length; i++){
     //commands[i] contains lines of the input
 }    
    });
}
else{
    console.log("Not a .k file!");
}

Notice the .split('\n'); function, that splits the string into an array at every '\n' occurrence. Hope it helps!
Categories: ,

4 comments: