CatherineAlv CatherineAlv - 24 days ago 6
Bash Question

How do I write a shell script using node to run multiple javascript files one after the other?

I want to write a .sh file to run multiple javascript files.

I know that I need the following lines:

#!/usr/bin/env node
chmod u+x ./a/file1.js ./a/file2.js


Is it correct to put two .js files one after the other? I need file1.js to execute first and then file2.js because some of the functions from file2.js need information outputted from file1.js.

I'm also a bit confused with the difference between #!/usr/bin/env node and #!/usr/bin/env bash. Will I still be able to run my .js files with bash?

Answer

#!/usr/bin/env node sets the environment to Node.js which is a JavaScript environment.

For example if you create a simple script test.js with the following content:

#!/usr/bin/env node

// now we're in JavaScript!
var d = new Date();

console.log('Current Time: ' + d);

Afterwards you make it executable:

$ chmod u+x test.js

Then you can execute it in the shell:

$ test.js
Current Time: Sun Nov 13 2016 07:14:15 GMT+0000 (GMT)

The file extension doesn't matter:

$ mv test.js test.sh
$ test.sh
Current Time: Sun Nov 13 2016 07:15:05 GMT+0000 (GMT)

If you don't want to change your JavaScript files so that they become shell scripts then you can run them from a shell script using Node.

tasks.sh:

#!/bin/sh
node ./a/file1.js
node ./a/file2.js

Afterwards make it executable and run it:

$ chmod u+x tasks.sh
$ tasks.sh