NodeJs Error: spawn C:\Windows\system32\cmd.exe; ENOENT - javascript

This is my script :
var exec = require('child_process').exec;
exec('dir', function(error, stdout, stderr) { // 'dir' is for example
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
And in the console I have :
exec error: Error: spawn C:\Windows\system32\cmd.exe; ENOENT
Someone can help me ?

This can also be caused if you are feeding in ExecOptions the options parameter, specifically 'cwd', and the path you provide is invalid
e.g:
cp.exec(<path_to_executable>, {
cwd: <path_to_desired_working_dir>
}, (err, stdout, stderr) => {
//......
})
If is not valid, the callback will be called with err equal to
Error: spawn C:\Windows\system32\cmd.exe ENOENT

I got to resolve the issue the problem is to remove the semicolon(;) from an end of the
ComSpec path C:\Windows\System32\cmd.exe
Mycomputer>properties>Advance System Settings>Environment Variables>System Variables
add this path:
ComSpec C:\Windows\System32\cmd.exe

The problem for me was that my solution directory was on a different drive than windows. Creating my solution on my C drive solved the issue.

Increasing the maxBuffer solved the problem for me.
const child_process = require('child_process');
var command = 'git ls-files . --ignored --exclude-standard --others';
child_process.execSync(command, {
maxBuffer: 1024 ** 6,
});

Related

Failing on sftp deploy, circle CI, nuxt

For several months I have been able to deploy to my server with no problems using Circle CI, ever since the outage 2 days ago, (not sure if things are related) my deployment script has been failing.
Here is the deployment script:
require('dotenv').config();
console.log("Starting upload")
var SftpUpload = require('sftp-upload'),
fs = require('fs');
var options = {
host: process.env.FTP_HOST,
username: process.env.FTP_UN,
password: process.env.FTP_PW,
path: './dist',
remoteDir: process.env.FTP_PATH,
// excludedFolders: ['**/.git', 'node_modules'],
// exclude: ['.gitignore', '.vscode/tasks.json'],
// privateKey: fs.readFileSync('privateKey_rsa'),
// passphrase: fs.readFileSync('privateKey_rsa.passphrase'),
dryRun: false,
}
console.log(options);
sftp = new SftpUpload(options);
console.log("sftp working ahead")
sftp.on('error', function(err) {
console.log(options)
console.log("igoring error for now")
//throw err;
})
.on('uploading', function(progress) {
console.log(options);
console.log('Uploading', progress.file);
console.log(progress.percent+'% completed');
})
.on('completed', function() {
console.log('Upload Completed');
})
.upload();
Here is the error
'
Starting upload
{
host: '************************',
username: '*********',
password: '************',
path: './dist',
remoteDir: '*****************************************',
dryRun: false
}
sftp working ahead
buffer.js:330
throw new ERR_INVALID_ARG_TYPE(
^
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
at Function.from (buffer.js:330:9)
at new Buffer (buffer.js:286:17)
at onNEWKEYS (/home/circleci/repo/node_modules/ssh2/lib/Connection.js:2282:29)
at Parser.<anonymous> (/home/circleci/repo/node_modules/ssh2/lib/Connection.js:123:5)
at Parser.emit (events.js:314:20)
at Parser.parsePacket (/home/circleci/repo/node_modules/ssh2/lib/Parser.js:468:12)
at Parser.execute (/home/circleci/repo/node_modules/ssh2/lib/Parser.js:249:14)
at Socket.<anonymous> (/home/circleci/repo/node_modules/ssh2/lib/Connection.js:523:18)
at Socket.emit (events.js:314:20)
at addChunk (_stream_readable.js:297:12) {
code: 'ERR_INVALID_ARG_TYPE'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! nyb.nyb.nyb#1.0.0 deploy: `node deploy-sftp.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the nyb.nyb.nyb#1.0.0 deploy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/circleci/.npm/_logs/2022-09-16T08_55_31_507Z-debug.log
Exited with code exit status 1
CircleCI received exit code 1
All of this happens after I installed the packages and built the static files that i'm sftp'ing to a server using nuxt generate. I'm confused about what is happening and how I might salvage my pipeline. Any suggestions are greatly appreciated, thank you!
While i did not find the cause of above error, i found a workaround by using the ssh2-sftp-client, documentation and source code is here
The new deployment script is as follows:
let SftpClient = require('ssh2-sftp-client');
const path = require('path');
require('dotenv').config()
const config = {
host: process.env.FTP_HOST,
username: process.env.FTP_UN,
password: process.env.FTP_PW,
port: process.env.FTP_PORT || 22
};
async function main() {
const client = new SftpClient('upload-test');
const src = path.join(__dirname, './dist/');
const dst = process.env.FTP_PATH;
try {
await client.connect(config);
client.on('upload', info => {
console.log(`Listener: Uploaded ${info.source}`);
});
let rslt = await client.uploadDir(src, dst);
return rslt;
} catch (err) {
console.error(err);
} finally {
client.end();
}
}
main()
.then(msg => {
console.log(msg);
})
.catch(err => {
console.log(`main error: ${err.message}`);
});
Hope this helps anyone encountering similar problems.

BATCH: How can I close running batch file by the name using node.js

I want to know how can I close running batch file using Child process or anything in node.js
This is an example for exec in child process
const { exec, spawn } = require('child_process');
exec('my.bat', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
In order to kill the spawned process when using 'child_process', you need to return the created ChildProcess reference, in this case by exec().
You can then kill the process using it's own API, ie. doing childProcess.kill().
Full example:
const { exec, spawn } = require('child_process');
const childProcess = exec('my.bat', (err, stdout, stderr) => {
// explicitly kill the process
childProcess.kill();
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
Find more details in the node.js docs
exec()
childProcess.kill()
If anyone is running into the issue that the batch file is not killable with .kill() or process.kill(processToKill.pid) or is starting another exe that is independent of the batch file, one solution that worked for me was to check the exe/process name I want to kill in the task manager and kill it with the (Windows) cmd command "taskkill /IM name.exe".
In code that looks like the following:
Executing the extra program (.bat, .exe, .lnk):
const systemprocess = require("child_process");
exampleVariable = systemprocess.exec("C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Accessories/Snipping Tool.lnk", (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
Killing the process:
systemprocess.exec(`taskkill /IM SnippingTool.exe`, (err, stdout, stderr) => {
if (err) {
throw err
}
if (stdout) {
console.log('stdout', stdout)
}
console.log('stderr', err)
});
Though if you execute another exe with spawn you should be able to kill it with varaibleNameOfChildProcess.kill(); like #Kworz answer suggests.
Instead of using exec use spawn, you might be able te retreive the PID generated by the bat file execution. Call process.kill(PID) to kill the running bat file
var spawn = require('child_process').spawn;
var child = spawn('my.bat', {detached: true});
process.kill(child.pid);

Child Process Exec Failed Electron App Calling nodejs SpeedTest

I tried to execute a nodejs command inside electron.
const { execFile } = require('child_process');
const child = execFile('node', ['--version'], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
That one above is fine! And give an output nicely.
But then once i execute :
npm install --global --save speed-test
under one of my Electron App.
And try to execute a different command such as:
const { execFile } = require('child_process');
const child = execFile('speed-test', null, (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
it gaves me an error:
Uncaught Error: spawn speed-test ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:264)
at onErrorNT (internal/child_process.js:456)
at processTicksAndRejections (internal/process/task_queues.js:80)
The more interesting part is that, If i execute the command itself under CommandPrompt of Nodejs, it's perfect! So... i'm confused.
What the things that i need to modify under the Electron App anyway?

Spawn python ENOENT in node.js

I am creating a node js script that interacts with both python and electron js to create a GUI. I am currently stuck at an error unfortunately. That error being:
Uncaught Error: spawn python ENOENT
This is on line 167 of events.js, a script that I have not been able to find. I have currently set my PYTHON env variable to C:\Python27\python.exe and my PYTHONPATH to C:\Python27.
Here is the code that is being run when this error occurs.
function getselectors() {
var ps = require("python-shell")
var path = require("path")
var amount = document.getElementById('para').value;
var options = {
scriptPath : path.join (__dirname, '/../engine/'), args : [amount]
}
ps.PythonShell.run ('test.py', options, function (err, results) {
if (err) throw err;
swal (results [0]);
});
}

Node.JS: execFile ENOENT

I've tried to execute *.exe file, but got:
exec error: { Error: spawn ${__dirname}/install.exe ENOENT
Code:
var execFile = require('child_process').execFile
execFile('${__dirname}/install.exe', function(error, stderr) {
console.log('stderr: ', __dirname);
if (error !== null) {
console.log('exec error: ', error);
}
});
Also tried: '${__dirname}\install.exe', './install.exe', 'D:\install.exe'
#FelixKling has the right advice; variables don't work unless you create your string with back-ticks. Additionally, it's a good idea to use the path module to resolve file paths:
var path = require('path');
var execFile = require('child_process').execFile;
var exePath = path.resolve(__dirname, './install.exe');
execFile(exePath, function(error, stderr) {
console.log('stderr: ', __dirname);
if (error !== null) {
console.log('exec error: ', error);
}
});
Edit:
This is for your original question, about ENOENT; for your second about UNKNOWN errors, the cause can vary. It sounds like it might be a permissions issue since the executable needs to elevate to administrator permissions.

Categories

Resources