Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you run a javascript file using node.js and bash script?

I'm new to programming in javascript. I am given a task to write a .js file that will run some input.json. I'm supposed to run it as such:

./name.js input.json

How can I incorporate node.js in this process and how do I get terminal to accept that script?

Thanks!

Edit: I solved my problem! I can't answer my own problem yet because of rules, anyway...

#!/usr/bin/env node
var fs = require('fs');

args = []
process.argv.forEach(function (val, index, array) 
{
    args.push(val); 
});

var file = fs.readFileSync(args[2], "UTF-8", function (err, data) 
{
if (err) throw err;
});

This is essentially what I did. I spent some time searching and combining things I found from different posts and got this to work - maybe it's not the best way, but it works. This stores my .json file into the file variable, which then I passed in as a function argument elsewhere. Thanks everyone.

like image 686
minzeycat Avatar asked Oct 28 '12 01:10

minzeycat


2 Answers

   #!/usr/bin/env node
   var commandLineArguments = process.argv.slice(2);
   ...
like image 53
Tim Boudreau Avatar answered Oct 20 '22 17:10

Tim Boudreau


Maybe too obvious, but the easiest way is:

node ./name.js input.json
like image 37
DanBaker Avatar answered Oct 20 '22 16:10

DanBaker