I am running php command from Node.js child_process.
In response it is showing error and throwing error with error code 255 because of which my script is breaking.
When i execute the command from terminal it works fine but in child_process it gives error.
async function decrypt(cipher){
try {
var terminal = require('child_process');
var util = require('util');
var exec = util.promisify(terminal.exec);
var command = "usr/bin/php " + basePath + "/decrypt.php '" + cipher +"'";
return await exec(command);
}catch(err){
console.log(err);
console.error(err.code +' | '+ err.message);
}
}
module.exports = {
decrypt : decrypt
}
{ Error: Command failed: /usr/bin/php /var/www/html/nodejs/decrypt.php 'w5oFS8U4NGrleFHtptkmO+luDMw0z+fYrJ/onlj6fndIS/0QrWzOAsTN450VLZwR+GmDkyylybGJXUnx2VdeJQ=='
at ChildProcess.exithandler (child_process.js:281:12)
at emitTwo (events.js:126:13)
at ChildProcess.emit (events.js:214:7)
at maybeClose (internal/child_process.js:915:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
killed: false,
code: 255,
signal: null,
cmd: '/usr/bin/php /var/www/html/nodejs/decrypt.php \'w5oFS8U4NGrleFHtptkmO+luDMw0z+fYrJ/onlj6fndIS/0QrWzOAsTN450VLZwR+GmDkyylybGJXUnx2VdeJQ==\'',
stdout: '\t\n\n{"error":false,"decryptedText":"0324"}',
stderr: '' }
Desired Output is : '{"error":false,"decryptedText":"0324"}'
The error trace stack is more important than the error code.
process exit code
Related
I've run npm install on mac using sudo and it installed with 0 vulnerabilities.
When I give npm start, I'm getting error code ELIFECYCLE with errno 1.
I'm able to run the same in windows without getting an error.
Below is the log of the run
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'start' ]
2 info using npm#6.4.1
3 info using node#v11.3.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle tanaaz#0.1.0~prestart: tanaaz#0.1.0
6 info lifecycle tanaaz#0.1.0~start: tanaaz#0.1.0
7 verbose lifecycle tanaaz#0.1.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle tanaaz#0.1.0~start: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Files/Taannaz/Taannaz Web/tanaaz-master/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
9 verbose lifecycle tanaaz#0.1.0~start: CWD: /Files/Taannaz/Taannaz Web/tanaaz-master
10 silly lifecycle tanaaz#0.1.0~start: Args: [ '-c', 'node scripts/start.js' ]
11 silly lifecycle tanaaz#0.1.0~start: Returned: code: 1 signal: null
12 info lifecycle tanaaz#0.1.0~start: Failed to exec start script
13 verbose stack Error: tanaaz#0.1.0 start: `node scripts/start.js`
13 verbose stack Exit status 1
13 verbose stack at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack at EventEmitter.emit (events.js:182:13)
13 verbose stack at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack at ChildProcess.emit (events.js:182:13)
13 verbose stack at maybeClose (internal/child_process.js:978:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:265:5)
14 verbose pkgid tanaaz#0.1.0
15 verbose cwd /Files/Taannaz/Taannaz Web/tanaaz-master
16 verbose Darwin 18.2.0
17 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
18 verbose node v11.3.0
19 verbose npm v6.4.1
20 error code ELIFECYCLE
21 error errno 1
22 error tanaaz#0.1.0 start: `node scripts/start.js`
22 error Exit status 1
23 error Failed at the tanaaz#0.1.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
Pls suggest the necessary.
I am sharing the lines in start.js as well below. Again this works completely fine in Windows 10 and throws me the error mentioned in MacOS Mojave
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const config = require('../config/webpack.config.dev');
const createDevServerConfig = require('../config/webpackDevServer.config');
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(`Learn more here: ${chalk.yellow('https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#advanced-configuration')}`);
console.log();
}
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web sever.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
you see the following
20 error code ELIFECYCLE
21 error errno 1
22 error tanaaz#0.1.0 start: `node scripts/start.js`
22 error Exit status 1
when the start.js reaches process.exit(1). if this is not expected, you should debug your code and fix that.
I am trying to run photoshop script through childprocess execsync using the following code, But am getting a error
try {
const child_process = require("child_process")
child_process.execSync('"C:/Program Files/Adobe/Adobe Photoshop CC 2019/Photoshop.exe" Z:/myfile.jsx', (err, stdout, stderr) => {
if (err) {
console.log("error here");
}
})
.on('close', function (code, signal) {console.log('go to next step')})
} catch (err) {
err.stdout;
err.stderr;
err.pid;
err.signal;
err.status;
}
But I am getting a error
{ Error: Command failed: "C:/Program Files/Adobe/Adobe Photoshop CC 2019/Photoshop.exe" Z:/Render2.0/psTextConvertor.jsx
at checkExecSyncError (child_process.js:611:11)
at Object.execSync (child_process.js:648:13)
at startPhotoshop (Z:\Render2.0\tempsqs.js:422:23)
at mergeFontData (Z:\Render2.0\tempsqs.js:410:9)
at ChildProcess.<anonymous> (Z:\Render2.0\tempsqs.js:282:21)
at ChildProcess.emit (events.js:187:15)
at ChildProcess.EventEmitter.emit (domain.js:442:20)
at maybeClose (internal/child_process.js:962:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:251:5)
status: 1,
signal: null,
output: [ null, <Buffer >, <Buffer > ],
pid: 5492,
stdout: <Buffer >,
stderr: <Buffer > }
but the script runs perfectly , but I am not getting exit code , please help
I had similar problems getting Photoshop to launch and run a script from node as a child process. I was working on a Windows system with Adobe CS6 at the time and was able to get this working by writing a powershell script to launch photoshop with args to execute an ExtendScript file, and then used child-process.exec to run that powershell script from node.
powershell:
Start-Process -FilePath "C:\Program Files\Adobe\Adobe Photoshop CS6 (64 Bit)\Photoshop.exe" -ArgumentList "C:\Scripts\MyScript.jsx" -Wait
node:
function runPowershell(path) {
var spawn = require("child_process").exec, child;
child = spawn(`powershell -ExecutionPolicy Bypass -File ${path} -NoExit`);
child.stdout.on("data", function (data) {
console.log("Powershell Data: " + data);
});
child.stderr.on("data", function (data) {
console.log("Powershell Errors: " + data);
});
child.on("exit", function () {
console.log("Powershell Script finished");
});
child.stdin.end(); //end input
}
runPowershell("path/to/powershellScript.ps1");
Question:
How do I run my python script in my node app?
This works:
From command line, I run this, and it works.
python generatePersonTerraform.py -s http://localhost:8080/api/person/239/exportPersonGeneration
Code that does not work in Node server.js
var PythonShell = require('python-shell');
...
var runPythonRoutine = function (request, response) {
var PythonShell = require('python-shell');
var options = {
mode: 'text',
pythonPath: 'python',
pythonOptions: ['-s'],
scriptPath: '.',
args: ['http://localhost:8080/api/person/135/exportPersonGeneration']
};
PythonShell.run('generatePersonTerraform.py', options, function (err, results) {
console.log(err);
});
}
Error:
at PythonShell.parseError (/root/my-app/node_modules/python-shell/index.js:191:17)
at terminateIfNeeded (/root/my-app/node_modules/python-shell/index.js:98:28)
at ChildProcess.<anonymous> (/root/my-app/node_modules/python-shell/index.js:89:9)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:194:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
executable: 'python',
options: [ '-s' ],
script: 'generatePersonTerraform.py',
args: [ 'http://localhost:8080/api/person/239/exportPersonGeneration' ],
exitCode: 1 }
Note
I have been trying to use https://www.npmjs.com/package/python-shell
EDIT 1
I changed the options to:
var options = {
mode: 'text',
pythonPath: 'python',
pythonOptions: [],
scriptPath: '.',
args: ['-s', 'http://localhost:8080/api/serviceType/135/exportPluginGeneration']
};
and got this error:
at PythonShell.parseError (/root/my-app/node_modules/python-shell/index.js:191:17)
at terminateIfNeeded (/root/my-app/node_modules/python-shell/index.js:98:28)
at ChildProcess.<anonymous> (/root/my-app/node_modules/python-shell/index.js:89:9)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:194:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
executable: 'python',
options: null,
script: 'generatePersonTerraform.py',
args:
[ '-s',
'http://localhost:8080/api/person/135/exportPersonGeneration' ],
exitCode: 0 }
But, it also ran and worked, it just stalls the node app. So, if I figure out how to make it not stall then I am all good. The python script seems to build all the files it is supposed to.
'-s' should be in args, not pythonOptions.
I'm using this code:
const {
spawn
} = require('child_process');
let info = spawn('npm', ["-v"]);
info.on('close', () => {
console.log('closed');
}
But I have this error:
events.js:182
throw er; // Unhandled 'error' event
^
Error: spawn npm ENOENT
at exports._errnoException (util.js:1022:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:189:19)
at onErrorNT (internal/child_process.js:366:16)
at _combinedTickCallback (internal/process/next_tick.js:102:11)
at process._tickCallback (internal/process/next_tick.js:161:9)
at Function.Module.runMain (module.js:607:11)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3
If I use instead:
let info = spawn('npm', ["-v"], {shell: true});
it works!
But why I need shell: true? I need also to see the stdout of that spawn, so I'm also using this:
let info = spawn('npm', ["-v"], {shell: true, stdio: 'inherit'});
It's correct?
While calling spawn itself, there is no npm command under spawn. Thus you got that error message. Instead of using spawn itself, while adding shell: true, spawn will use shell of your system to run that command. Since your system has npm, it works.
let info = spawn('npm', ["-v"], {shell: true, stdio: 'inherit'}); It's correct?
The code is fine if your parameters of spawn are controllable. But generally, I suggest use pure spawn without using shell. The risk will reduce without touching shell directly.
Since you need the stream return from spawn. I have checked other solution here. Without shell: true, You can use the code:
const {
spawn
} = require('child_process');
let projectPath = ''//the path of your project
let info = spawn('npm', ['-v'], { cwd: projectPath });
let result = '';
info.stdout.on('data', function(data) {
result += data.toString();
console.log(result);
}
I am very new to node.js,
I am trying to create a node.js script with the execution of shell script in it.
Here is the code which i have .
var spawn = require('child_process').spawn
var _ = require('underscore');
var deploySh = spawn('sh', [ 'vij.sh' ], {
cwd: process.env.HOME + '/u/qa/gv/node/scripts',
env:_.extend(process.env, { PATH: process.env.PATH + ':/usr/local/bin' })
});
and when i try to execute it, i am facing the below issue. Can anyone help me on this?
node vijay
events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
at errnoException (child_process.js:988:11)
at Process.ChildProcess._handle.onexit (child_process.js:779:34)
spawn is complaining that it can't find 'sh', use 'bash' instead (you might also need to specify the full path to your script depending on your env setup.)
so I'd try:
spawn('bash', ['vij.sh'], ...
spawn('bash', ['/my/path/to/vij.sh'], ...
spawn('/my/path/to/vij.sh', [], ...
var spawn = require('child_process').spawn
var _ = require('underscore');
var deploySh = spawn('sh', [ 'vij.sh' ], {
// cwd: process.env.HOME + '/u/qa/gv/node/scripts',
env:_.extend(process.env, { PATH: process.env.PATH + ':/usr/local/bin' })
});
Comment cwd: line no. 4
Until now I don't know what is process.env.HOME value but this worked for me.