Search code examples
node.jsbrowserify

Run Node Package + Arguments from another script


I've found myself in a situation where I'm having to run a single command e.g. node compile.js

that .js file needs to run the following

browserify -t jadeify client/app.js -o bundle.js

All the dependencies are installed, and by running this command in the CLI works fine, just need to figure out how to execute it from within a node script.

We've also got inside our package.json the following which contains something similar to

"script" : [ "compile": "browserify -t jadeify client/app.js -o bundle.js" ] this works perfectly when you execute cd /project && npm run compile via ssh however not via exec

Thanks


Solution

  • You can access script arguments via process.argv.

    An array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

    You can then use the browserify api together with jadeify to get what you need.

    var browserify = require('browserify')();
    var fs = require('fs');
    
    var lang = process.argv[2];
    console.log('Doing something with the lang value: ', lang);
    
    browserify.add('./client/app.js');
    browserify.transform(require("jadeify"));
    browserify.bundle().pipe(fs.createWriteStream(__dirname + '/bundle.js'));
    

    Run it with $ node compile.js enGB