Run npm install programmatically in specified folder - node.js

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?

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
});

If you're using Nodejs, which I think you are, you can run
child_process.exec('npm install') // or any other command which you give from terminal or command prompt
Check the documentation for child_process
https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

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

Start nestjs project as a Windows service

We used to start Angular and NestJS (based on node.js) projects using Docker containers. This solution was discontinued for various reasons, so we are looking for a way to start these projects at the start of the PC (or on a trigger) and restart the project automatically if a crash occurs.
node-windows
This package builds a Windows service from a node.js project. NestJS being based on node.js, starting it using node.js is done this way (while in the project's folder):
node PATH_TO_PROJECT\node_modules\#nestjs\cli\bin\nest.js start --config .\tsconfig.build.json
The script used:
const svc = new Service({
name: 'Test',
description: 'Test',
script:
'PATH_TO_PROJECT\\node_modules\\#nestjs\\cli\\bin\\nest.js',
scriptOptions: [
'start --watch --config PATH_TO_PROJECT\\tsconfig.build.json',
],
],
execPath: 'C:\\Program Files\\nodejs\\node.exe',
});
svc.on('install', function () {
console.log('installed');
svc.start();
});
svc.install();
The installation works as intended but in a browser, the server cannot be reached.
Questions
Is there a way to use node-windows for a NestJS project?
Is it possible to use an absolute path with the nest cli start command? (e.g nest start --config ABSOLUTE_PATH)
How would you start an Angular project the same way?
Thank you.
am use 'child_process' lib for run command
like this
server.js
const { exec } = require("child_process");
exec("npm run start", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
and use node-windows like this
var Service = require('node-windows').Service;
var serviceDetail = require('./servicename')();
console.log(serviceDetail);
// Create a new service object
var svc = new Service({
name: serviceDetail.name,
description: serviceDetail.detail,
script: './server.js'
});
console.log('start building up service name ' + serviceDetail.name);
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
svc.install();

How to generate angular application using child_processes.spawn() method in a specific directory?

I have recently started to study about node and I wanted the node server should use:
ng new my-app
To create application without manually typing in the terminal.
I found that we could run command using child_processes.spawn() or child_processes.exec() in node.
I cannot understand why am i not able to do so with the below code?
spawn("ng",[join("ng new ", folderName," --directory ", workspaceName)]);
I am new to this topic so I would require your help to understand this.
Try This
var spawn = require('child_process').spawn;
var child = spawn('npm install -g #angular/cli && cd your directory && ng new my-dream-app', {
shell: true
});
child.stderr.on('data', function (data) {
console.error("STDERR:", data.toString());
});
child.stdout.on('data', function (data) {
console.log("STDOUT:", data.toString());
});
child.on('exit', function (exitCode) {
console.log("Child exited with code: " + exitCode);
});

How I can create build file with Node.JS script?

How I can do it with Node.js(script file not in cmd consol):
go to the folder with the project
do npm i
do webpack -p
?
Create a bash script with all you want to do:
yourbash.sh:
cd /yourdirectory
npm i
webpack -p
then just spawn this process in your node
const spawn = require('child_process').exec
spawn('sh yourbash.sh', [], function (err, stdout, stderr) {
if (err) { console.log(err) } // handle error
// standard output from the bash script
console.log(stdout)
})
Alternatively, you can skip the bash file entirely by doing this:
const spawn = require('child_process').exec
spawn('cd /yourdirectory && npm i && webpack -p', [], function (err, stdout, stderr) {
if (err) { console.log(err) } // handle error
// standard output from the bash script
console.log(stdout)
})

API HOST name from env variable node js

I have got a react app where I need to dynamically pass the API HOST name from environment (docker run --env API_HOST=localhost)
I'm using a child process in gulp to run 'node node.js'
//run npm install then node app
cp.spawn('npm install' ,{cwd:NODE_APP_FOLDER,env:process.env}, function(error, stdout, stderr) {
if (error) {
console.error(`exec error: ${error}`);
return;
}
var server = cp.spawn('node', ['app.js'], {
cwd: NODE_APP_FOLDER,
env: {
API_HOST:'localhost'
}
});
}
but in my code within the app process.env.API_HOST return undefined
Any help would be much appreciated

Update NPM modules from within grunt

I'm trying to automate the update of new node modules but, npm update seems not to want to run correctly from within grunt also updating the package.json file with the new version. I want to do this regardless of what version is specified in the package.json file.
What I found till now is the node module: npm-check-updates (https://www.npmjs.com/package/npm-check-updates)
The problem is that I can't get it to work with other modules like npm-shell or npm-exec.
I've tried using npm update -D directly, but that fails too.
I'm asking if it can be done.
Here's what I use:
grunt.registerTask('update', 'Update npm modules', function() {
var exec = require('child_process').exec;
var cb = this.async();
exec('npm update -D', {}, function(err, stdout) {
console.log(stdout);
cb();
});
});
If i'm correct you're trying to update ALL of your npm packages inside of your package.json file? I would recommend using this package.
Install the package.
npm install grunt-auto-install --save-dev
Add it to your grunt tasks.
grunt.loadNpmTasks('grunt-auto-install');
Then add the configuration to your gruntfile.js
grunt.initConfig({
auto_install: {
local: {},
subdir: {
options: {
cwd: 'subdir',
stdout: true,
stderr: true,
failOnError: true,
npm: '--production'
}
}
},
});
Here is the reference:
https://www.npmjs.com/package/grunt-auto-install
AFTER YOUVE UPDATED THE PACKAGES
Update your devDependencies and dependencies automatically with a grunt task.
Install the npm module to update your packages in your dev dependencies object.
npm install --save-dev grunt-dev-update
Add it to your grunt tasks.
grunt.loadNpmTasks('grunt-dev-update');
Add your configuration to your gruntfile.
devUpdate: {
main: {
options: {
//task options go here
}
}
}
Reference:
https://www.npmjs.com/package/grunt-dev-update
I found a solution using npm-check-update (ncu) and grunt.util.spawn:
// Install NPM Updates
grunt.registerTask('update-npm', 'Update package.json and update npm modules', function() {
grunt.log.writeln('If you get an error here, run "npm install -g npm-check-updates".');
grunt.task.run('npm-write-new');
grunt.task.run('npm-update');
});
// Check for npm module updates
grunt.registerTask('npm-check', 'Check for npm modules updates', function() {
var done = this.async();
grunt.log.writeln('Checking for npm modules updates ...');
grunt.util.spawn({
cmd: 'ncu',
args: '',
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('No files were modified.');
done();
});
});
// Write new versions to packages.json
grunt.registerTask('npm-write-new', 'Write new versions to package.json', function() {
var done = this.async();
grunt.log.writeln('Checking for npm modules updates ...');
grunt.util.spawn({
cmd: 'ncu',
args: ['-u'],
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('New versions were written to "package.json".');
done();
});
});
// Update npm modules
grunt.registerTask('npm-update', 'Update npm modules', function() {
var done = this.async();
grunt.log.writeln('Installing npm modules updates ...');
grunt.util.spawn({
cmd: 'npm',
args: ['update','--loglevel','warn'],
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('NPM modules were updated.');
done();
});
});

Resources