大前端

node执行cmd或shell命令

2021-10-08  本文已影响0人  天問_专注于大前端技术
Tiven

在实现前端工程化的过程中,经常需要在一个js脚本中去执行其他node/npm或者其他shell命令。本篇就介绍两种node调用shell的方法。

Node执行Shell命令

一、node原生模块:child_process

const process = require("child_process");

// 执行 npm run build 命令
;(function() {
  process.exec('npm run build', (error, stdout, stderr) => {
    if (!error) {
      // 成功
    } else {
      // 失败
    }
  });
})();

二、npm包:shelljs

npm i -D shelljs
const shell = require('shelljs');

// 同步
// 执行 git status 命令
const { code } = shell.exec('git status');

/*
* 返回一个对象
* 可以根据 code 值来判断当前命令是否执行成功
* code === 0 代表成功
* */

// 异步回调
// 执行 git add . 命令
shell.exec('git add .', function(code, stdout, stderr) {
  console.log('Exit code:', code);
  console.log('Program output:', stdout);
  console.log('Program stderr:', stderr);
  if (code===0) {
    console.log('成功')
    // do something
  }
});

参考文档:


欢迎访问:个人博客地址

上一篇 下一篇

猜你喜欢

热点阅读