Relative path does not work in child_process / node - node.js

Below is the current code I use in a Gulp task to run a bat file. The path is absolute.
var gulp = require('gulp');
var exec = require('child_process').exec;
module.exports = function() {
// Merges the CSS and JS files
return exec("C:/git/xxxx/Config/BuildScripts/buildassets.bat",
function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
}
);
};
I want to make it as relative path, but when I change it to a relative path,
return exec('../../../Config/BuildScripts/buildassets.bat'
I get the following error:
'..' is not recognized as an internal or external command,
operable program or batch file.
How can I reference this file relatively?

I am doing this for that purpose but in my main process not in gulp file.
const app = electron.app;
const exec = require('child_process').exec;
var path = app.getAppPath();
exec(`"${path}\\path\\toexe.exe"`, function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
});

Instead of using /, use \\:
return exec('..\\..\\..\\Config\\BuildScripts\\buildassets.bat', function() {
...
})

Related

Execute Multiple .js Files From Terminal In Sequence

I have about 100 JS files with each having different script.
file1.js , file2.js , file3.js , ... , file100.js
Right now, to execute each file I have to go to my terminal and do this:
node file1
node file2
node file3
.
.
node file100
That means I have to do this 100 times in the terminal. Is there a script to write in a JS file so I can execute ONLY ONE JS file that would execute all the 100 JS files in sequence?
I also want to give 3 seconds waiting between each execution which I believe I can achieve with the following code:
var interval = 3000;
var promise = Promise.resolve();
promise = promise.then(function () {
return new Promise(function (resolve) {
setTimeout(resolve, interval);
});
});
Any suggestion how to execute all the 100 JS files without typing node file# 100 times in the terminal?
here is a script that does that, you can also choose a different file format rather than
node file1
..
node filex
you can do this file1,file2,file3...filex,also look into child_process before using this code.
const { readFileSync } = require('fs');
const {exec} = require("child_process");
function executeEachFile(command){
exec(command, (error, stdout, stderr) => {
if(error){
console.log(error);
}
console.log("stdout: " + stdout)
});
}
function readFile(path){
const output = readFileSync(path,"utf8").split("\n").map(file=>{
return file.replace("\r","");
});
console.log(output)
return output
};
function IntervalLoop(ArrayofFiles){
let counter = 0;
const interval = setInterval(()=>{
const commandName = "node "+ ArrayofFiles[counter];
console.log(commandName);
executeEachFile(commandName);
counter++;
console.log(counter);
if (ArrayofFiles.length == counter){
clearInterval(interval);
}
},300)
}
const fileNames = readFile("exec.txt");
IntervalLoop(fileNames);

node.js on windows : Is it possible to get the absolute path of process from its pid?

I would like to get the path of a running process on Windows os
I can find his pid in node.js
var exec = require('child_process').exec;
exec('tasklist', function(err, stdout, stderr) {
var lines = stdout.toString().split('\n');
var results = new Array();
lines.forEach(function (line) {
if (line.indexOf('GestionDocument') > -1) {
console.log(line);
var parts = line.split(/[\s,]+/);
console.log(parts[1]);
}
});
that displays me
16248
Do you know how to get path folder of a process from his pid?

Run all js files sequentially with console log

I need to execute some js files one after another, those js files are printing important information in the console.log.
I'm currently trying to use the following code, but it is not showing the console.log for sub js files.
How can I get this approach to work?
const fs = require('fs')
const exec = require('child_process').exec
const async = require('async') // npm install async
const path = require('path');
const scriptsFolder = path.resolve("./") + "\\" named scripts
const files = fs.readdirSync(scriptsFolder)
const targetFiles = files.filter(function (file) {
return path.extname(file).toLowerCase() === '.js';
});
const funcs = targetFiles.map(function (file) {
return exec.bind(null, `node ${scriptsFolder}${file}`)
})
function getResults(err, data) {
if (err) {
return console.log(err)
}
const results = data.map(function (lines) {
return lines.join('')
})
console.log(results)
}
async.series(funcs, getResults)
As there is no interaction between the js files, I just use a batch script to run all of them sequentially as below
for /R %%f in (*.js) do if not %%f==%~dpnx0 node "%%f"
Why do you execute each js file in seperate process?
Try to require the files one after the other, with no child_process
Check this answer for great example of dynamic require of folder.
You can consider running the scripts using execSync and use the stdio: "inherit" option to direct output form each script to the parent process:
const files = fs.readdirSync(scriptsFolder)
const targetFiles = files.filter(function (file) {
return path.extname(file).toLowerCase() === '.js';
});
for (let file of targetFiles) {
execSync(`node ${scriptsFolder}/${file}`, {
stdio: 'inherit'
});
}

Run Bash-Script within Electron App using child_process.exec

I'm struggling with running a bash-script within main.html.
const exec = require("child_process").exec;
// Execute bash script
exec("/c/workspace/_edu_zone/Proxy_Manager/filemover.sh", shellCallback);
// Callback
function shellCallback(error, stdout, stderr) {
console.log(error, stdout)
}
I'm always getting the error: no such file or directory. What am i doing wrong?
Any help is highly appreciated.
change
/c/workspace/_edu_zone/Proxy_Manager/filemover.sh
to
c:/workspace/_edu_zone/Proxy_Manager/filemover.sh
or
your could try using node-powershell to execute the command directly
const shell = require('node-powershell')
let ps = new shell({
executionPolicy: 'Bypass',
noProfile: true
});
function lunchnode() {
process.stdout.write('logging');
ps.addCommand('node run.js')
ps.invoke()
.then(function (output) {
process.stdout.write(output)
}).catch(function (err) {
process.stdout.write(err)
ps.dispose()
})
}

NodeJS exec() command for both Windows and Ubuntu

Using NodeJS, NPM, and Gulp.
I want to build a gulp task to run JSDoc that works on Ubuntu and Windows.
This works on Ubuntu...
var exec = require('child_process').exec;
return function(cb) {
exec('node node_modules/.bin/jsdoc -c jsdoc-conf.json', function(err, stdout, stderr) {
cb(err);
});
};
And this works on Windows...
var exec = require('child_process').exec;
return function(cb) {
exec('node_modules\\.bin\\jsdoc -c jsdoc-conf.json', function(err, stdout, stderr) {
cb(err);
});
};
Needless to say, neither works on the other. How do others solve this type of problem?
Try using path.resolve, which should provide you with a full path to the file regardless of the platform.
Node has process.platform, which... "returns a string identifying the operating system platform on which the Node.js process is running. For instance darwin, freebsd, linux, sunos or win32"
https://nodejs.org/api/process.html#process_process_platform
var exec = require('child_process').exec;
return function(cb) {
if (process.platform === 'win32') {
// Windows OS
} else {
// everything else
}
};
Using path.resolve:
const exec = require('child_process').exec;
const path = require('path');
return function(cb) {
let command = `node ${path.resolve('node_modules/.bin/jsdoc')} -c jsdoc-conf.json`;
exec(command, function(err, stdout, stderr) {
cb(err);
});
};

Resources