简体   繁体   中英

NodeJS exec() command for both Windows and Ubuntu

Using NodeJS, NPM, and Gulp.

I want to build a gulp task to run JSDoc that works on Ubuntu and Windows.

This works on Ubuntu...

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

return function(cb) {
  exec('node node_modules/.bin/jsdoc -c jsdoc-conf.json', function(err, stdout, stderr) {
    cb(err);
  });
};

And this works on Windows...

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

return function(cb) {
  exec('node_modules\\.bin\\jsdoc -c jsdoc-conf.json', function(err, stdout, stderr) {
    cb(err);
  });
};

Needless to say, neither works on the other. How do others solve this type of problem?

尝试使用path.resolve ,它应该为您提供文件的完整路径,而不管平台如何。

Node has process.platform , which... "returns a string identifying the operating system platform on which the Node.js process is running. For instance darwin , freebsd , linux , sunos or win32 "

https://nodejs.org/api/process.html#process_process_platform

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

return function(cb) {
  if (process.platform === 'win32') {
    // Windows OS
  } else {
    // everything else
  }
};

Using path.resolve :

const exec = require('child_process').exec;
const path = require('path');

return function(cb) {
  let command = `node ${path.resolve('node_modules/.bin/jsdoc')} -c jsdoc-conf.json`;

  exec(command, function(err, stdout, stderr) {
    cb(err);
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM