0

I have a Node project with the following structure:

.
├── index.js
├── package.json
├── updater.js
└── yarn.lock

I'm using Yarn with this project.

Inside file: package.json there is a reference to package: @emotion/core@^10.0.22 as you can see below:

{
  "name": "my-project",
  ...
  "dependencies": {
    ...
    "@emotion/core": "^10.0.22",
    ...
  }
  ...
}

What I need is:

From inside file: updater.js file, upgrade package: @emotion/core to version: ^10.0.27 (just in case, remember I'm using Yarn), so I can do:

$ node updater.js

From the command line I can achieve this very easily with:

$ yarn upgrade @emotion/core@^10.0.27

But I need to do this from inside the file: updater.js (this is a requirement). This is a simplification of a biggest problem (so I need to meet the requirements of this dummy use case even if it doesn't make sense).

This code will go inside a custom package that will take care of installing some other packages.

Thanks in advance!

Viewsonic
  • 827
  • 2
  • 15
  • 34
  • You will most likely have to run a script inside of `updater.js` that uses something like the `child_process` native module, see here - https://stackoverflow.com/a/35586247/5862900 – goto Feb 10 '20 at 21:38

1 Answers1

2

The easiest will be using child_process to execute any script:

const { exec } = require('child_process');

 const childProcess = exec('yarn upgrade @emotion/core@^10.0.27', (error, stdout, stderr) => {
     console.log('stdout: ' + stdout);
     console.log('stderr: ' + stderr);
     if (error !== null) {
          console.log('exec error: ' + error);
     }
 });

You can check out more at node.js document page

You can pipe the stdio for close-to-realtime outputs by doing:

childProcess.stdout.pipe(process.stdout)

But beware using *Sync (like execSync) libraries, you should NOT block code whenever possible. Better using callback or make it Promise

Also there are wonderful packages like shelljs to encapsulate this.

Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35
  • this approach works but there is a problem with it, the output is not in real time. I mean, it seems that yarn is doing all his job on the background without giving the user any feedback and at the end when everything is done, al the output is shown to the user at once. Any idea on how to solve this? Thanks! – Viewsonic Feb 10 '20 at 21:53
  • 1
    @Viewsonic https://stackoverflow.com/questions/22337446/how-to-wait-for-a-child-process-to-finish-in-node-js or https://stackoverflow.com/questions/4443597/node-js-execute-system-command-synchronously – goto Feb 10 '20 at 21:58
  • As @goto1 said you can easily pipe the output. – Aritra Chakraborty Feb 10 '20 at 22:00