Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

node.js - npm package.json OS specific script

I would like to create a package.json build script that executes slightly different set of commands when run from Windows, Linux, Mac.

The problem is that I cannot find a way to put it in package.json file that will run without problems at every system.

Here is an example that I would like to have:

"scripts" : {
    "build.windows" : "echo do windows specific stuff",
    "build.linux" : "echo do linux specific stuff",
    "build.mac" : "echo do mac specific stuff",
    "build" : "??????????????" <- what to put here to execute script designed for OS
                                  on which npm is running
}
question from:https://stackoverflow.com/questions/45082648/npm-package-json-os-specific-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use scripts with node run-script command. npm run is a shortcut of it.

Package json:

"scripts" : {
    "build-windows" : "node build-windows.js",
    "build-linux" : "node build-linux.js",
    "build-mac" : "node build-mac.js",
    "build" : "node build.js"
}

Command line:

npm run build-windows

If you don't like it, you can use commands inside node.js.

Package json:

"scripts" : {
    "build" : "node build.js"
}

Build.js

var sys = require('sys');
var exec = require('child_process').exec;
var os = require('os');

function puts(error, stdout, stderr) { sys.puts(stdout) }

// Run command depending on the OS
if (os.type() === 'Linux') 
   exec("node build-linux.js", puts); 
else if (os.type() === 'Darwin') 
   exec("node build-mac.js", puts); 
else if (os.type() === 'Windows_NT') 
   exec("node build-windows.js", puts);
else
   throw new Error("Unsupported OS found: " + os.type());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...