To do so I need some things:
- Read a file
- Make sure it's a .k file
- Split it line by line
- 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!
you have started great blog for Nodejs. its very useful for new.
ReplyDeleteDigital Menu for restaurants
eMenu App For Restaurants
Restaurant online ordering app
mobile food ordering software
Hey That was a great read, very informative, though native java debugging is not something I am good at i really liked this article, Check this out for a little more info.
ReplyDeleteAngular JS
NodeJS is great but i am a ReactJS guy, I mean it' easy to code and understand, there are many NodeJS Development Companies which build great apps for their clients.
ReplyDeleteGreat post and thanks for sharing such a useful information
ReplyDeletemobile app development company| web app development company|cloud app development company|saas app development company|custom mobile app & web app development company|mobile app and web app maintenance services|seo services | seo company|digital marketing company|Paid marketing services | ppc service providers