4

I'd like to run yarn commands programmatically from node.js, but can't find any sdk or cli utility. The only thing is to spawn a new process, but that's hacky...

Hanxue
  • 12,243
  • 18
  • 88
  • 130
Totty.js
  • 15,563
  • 31
  • 103
  • 175

1 Answers1

10

As of January 2019, Yarn does not have an API that you can call directly. You cannot require Yarn and use yarn commands similar to npm

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

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

You can only use node's child_process to execute the yarn command.

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}`);
});
Hanxue
  • 12,243
  • 18
  • 88
  • 130
  • This works, but would not give any feedback about the installation during the process. Is there a way to do that? – Merc Oct 12 '19 at 08:37
  • Also if I call a terminal command which needs interactive input (using inquirer.js > https://github.com/SBoudrias/Inquirer.js) I don't see any feedback. Do you know how I could solve this problem? – Merc Oct 12 '19 at 09:08
  • @Merc you can try with `spawn` instead of `exec`: https://stackoverflow.com/questions/48698234/node-js-spawn-vs-execute#:~:text=The%20main%20difference%20is%20the,try%20to%20execute%20your%20process. – Jose Jul 19 '20 at 05:40
  • 1
    Looks like `require('npm')` no longer works either in npm `v6.14.13`. – Kevin Ghadyani Aug 02 '21 at 21:36
  • OP said you cannot do that, so I doubt that that ever worked even in older versions of npm – Blaine Aug 05 '21 at 07:32