如何从node.js以编程方式运行`yarn tag`?

Tot*_*.js 3 node.js yarnpkg

我想从 node.js 以编程方式运行 yarn 命令,但找不到任何 sdk 或 cli 实用程序。唯一的事情就是产生一个新的进程,但这很麻烦......

Han*_*xue 5

截至 2019 年 1 月,Yarn 没有可以直接调用的 API。你不能要求 Yarn 并使用类似于 npm 的 yarn 命令

var npm = require('npm');
npm.load(function(err) {
  // handle errors

  // install module ffi
  npm.commands.install(['ffi'], function(er, data) {
    // log errors or data
  });
Run Code Online (Sandbox Code Playgroud)

只能使用节点的 child_process来执行 yarn 命令。

const { exec } = require('child_process');
exec('yarn add package@beta', (err, stdout, stderr) => {
  if (err) {
    // node couldn't execute the command
    return;
  }

  // the *entire* stdout and stderr (buffered)
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});
Run Code Online (Sandbox Code Playgroud)