Run npm install programmatically in specified folder

Viewed 3531

I want to run npm install via typescript code in a specified directory.

I found this code:

npm.load({}, function(err: any) {
    // handle errors

    // install module ffi
    npm.commands.install(["hello-world@0.0.1"], function(err: any, data: any) {
    // log errors or data
    });

    npm.on('log', function(message: any) {
    // log installation progress
    console.log(message);
    });
});

But now I don't want to install hello-world, but just run npm install (without any package).

Additionally it should run in a path that I can specify, like ./folder/subfolder

How can I do that?

3 Answers

Apart from exec it's also possible to use the npm package:

import * as cp from 'child_process';
var npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';

var path = '/path_to_npm_install';
const result = cp.spawnSync( npm, ['install'], {
     cwd: path
}); 

You can create a nodejs script that expect the directory path from user and create a child process and execute that command in that.

index.js

const { exec } = require('child_process');
exec(`cd /${process.env.PATH} | npm install`, (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});


PATH=/path_of_directory_to_run_npm_install node index.js

Read more about child_process from nodejs documentation - https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

Related