node execFile python script in aws lambda - javascript

I am trying to execute a script through a node service hosted on AWS lambda, but consistently get a ENOENT exception.
2020-04-22 07:55:14.613 (-04:00) 9c8c54fc-2aa2-4d17-89d9-ca1e404191b7 ERROR Error: spawn ./bin/test-bin.py ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
at onErrorNT (internal/child_process.js:469:16)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
errno: 'ENOENT',
code: 'ENOENT',
syscall: 'spawn ./bin/test-bin.py',
path: './bin/test-bin.py',
spawnargs: [ 1, 2 ],
cmd: './bin/test-bin.py 1 2'
}
Executing cat bin/test-bin.py in the child process spits out the source code of the script, ls -l through the child process shows that the script is executable, and the same code works locally on my linux machine.
const { execFile } = require('child_process');
execFile('cat', ["bin/test-bin.py"], (err, out) => {
if (err) {
console.error(err)
}
else {
console.log(out)
}
});
The script:
#!/usr/bin/python
import sys
import time
def sum(n1, n2):
return int(n1) + int(n2)
print(sum(sys.argv[1], sys.argv[2]))

Your python script is not a standalone executable - it relies on the shell interpreting the #!/usr/bin/python line at the top of the file to load the python interpreter (/usr/bin/python), and then run the script.
Because execFile doesn't load a shell, it won't do this. You could just use exec instead of execFile, but this is less safe, and slower.
Instead, run /usr/bin/python with execFile, with your script as an argument:
execFile('/usr/bin/python', ['bin/test-bin.py'], (err, out) => {
// ...
});

Related

nodejs: valid command line prompt doesn't exec or spawn with ENOENT error

I have a bash command (debian 10, GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)):
documents=("/data/sice.pdf" "/das00/12ser.pdf");bash ./clean-pdfs.sh "${documents[*]}"
that works when I paste into terminal.
However invoking it with either exec or spawn fails without giving clear error message.
When I ran it with exec I got some complaints about the brackets. Remembering the output is quite large, I opted for spawn
const { exec } = require('child_process');
command = `documents=(${pdfPaths});` + 'bash ./clean-pdfs.sh "${documents[*]}"'
console.log(command);
const subProcess = require('child_process')
const lsChildProcess = subProcess.spawn(command)
lsChildProcess.stdout.on('data', (data) => {
console.log(data);
})
lsChildProcess.on('error', function(err) {
console.log(err);
});
and after running this nodejs script I get the following error message that isn't very helpful (i changed the paths for security reasons):
{ Error: spawn documents=("/data/Traa.pdf" "/dater.pdf");bash ./clean-pdfs.sh "${documents[*]}" ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
at onErrorNT (internal/child_process.js:415:16)
at process._tickCallback (internal/process/next_tick.js:63:19)
errno: 'ENOENT',
code: 'ENOENT',
syscall:
'spawn documents=("/daice.pdf" "/daer.pdf");bash ./clean-pdfs.sh "${documents[*]}"',
path:
'documents=("/dace.pdf" "/daer.pdf");bash ./clean-pdfs.sh "${documents[*]}"',
spawnargs: [] }
The option shell is required here to (both conditions apply):
parse multiple commands separated by ";"
run commands that are not executable, like assigning an environment variable with document=.
To have the output of the spawned process printed to the console, we can use the option stdio: 'inherit'.
Both settings are documented here: https://nodejs.org/api/child_process.html#child_processspawncommand-args-options
And here is my version of the code that I was able to test succesfully on a zsh terminal. I'm using spawnSync because it's easier to handle without a callback, but spawn works just as well.
const pdfPaths = '"/data/sice.pdf" "/das00/12ser.pdf"';
command = `documents=(${pdfPaths});` + 'bash ./clean-pdfs.sh "${documents[*]}"'
console.log(command);
const subProcess = require('child_process')
subProcess.spawnSync(command, { shell: true, stdio: 'inherit' })

Electron NodeJS spawn error when running certain commands: spawn ENOENT

So, I'm trying to use spawn in my Electron application to run the flutter --version command.
This command works perfectly fine on my terminal.
Every solution I've seen implies I don't have it in my process.env.PATH variable. But when I do a console.log( process.env.PATH );, the path to my Flutter command is there.
Here is the current code I'm trying to execute:
const flutterVer = spawn('flutter', ['--version', '/c']);
flutterVer.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
Which returns:
Uncaught Error: spawn flutter ENOENT
at __node_internal_captureLargerStackTrace (node:internal/errors:464:5)
at __node_internal_errnoException (node:internal/errors:594:12)
at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
at onErrorNT (node:internal/child_process:477:16)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
I tried testing with another command, like git --version, and that worked perfectly fine.
I've found a neat workaround by using exec instead of spawn like so.
const { exec } = require('child_process');
const flutterVer = exec('flutter --version');
flutterVer.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
Will have too look into what the differences are between exec and spawn, but for now, it does what I need.

How to catch EPERM error on child process

Sometimes I've been getting this error while using puppeteer but since I haven't found a way around it. I just wrote code that will unlink it after the browser closes. Although sometimes Puppeteer will crash the whole process when this happens.
Is there a way to detect this crash and be able to do error handling?
[Error: EPERM: operation not permitted, unlink 'C:\Users\user\AppData\Local\Temp\puppeteer_dev_chrome_profile-8gwzA9\CrashpadMetrics-active.pma'] {
errno: -4048,
code: 'EPERM',
syscall: 'unlink',
path: 'C:\\Users\\user\\AppData\\Local\\Temp\\puppeteer_dev_chrome_profile-8gwzA9\\CrashpadMetrics-active.pma'
}
Right now I'm using child.on("error", exithandler) but it doesn't seem to work on this error.
var child = spawn(process.execPath, [__filename, "child"], {
stdio: ["inherit", "inherit", "inherit", "ipc"],
});
child.on("error", (err) =>{
console.log(`process ${child.pid} crashed with error: ` + err)
})

Can you help me to solve this error about json?

I'm trying to connect Firebase using node.js
I have following code in my json file.
const functions = require('firebase-functions');
const hmac_sha256= require ('crypto-js/hmac_sha256');
const request= require('request');
const admin= require('firebase-admin');
const service_Account= require('./service_account_key.json');
const firebaseConfig= json.parse(process.env.FIREBASE_CONFIG);
firebaseConfig.credential= admin.credential.cert("service_Account");
admin.initializeApp(firebaseConfig);
exports.getCustomToken = functions.https.onRequest((req,res)=>{
const accessToken= req.query.access_Token;
const FacebookAppSec= '72100b8d4ee21a85fc67d014f3b0c9fa';
const AppSecretProof= hmac_sha256(accessToken,FacebookAppSec);
//Validate token...
const uri='https://graph.accountkit.com/v1.1/me?access_Token=${accessToken}&App_Proof=${AppSecretProof}';
request({
url= uri,
json:true
},(error,fbresponse,data)=>{
if(error)
{
console.error('Access Token validation request failed\n',error);
res.status(400).send(error);
}
else if(data.error)
{
console.error('Invalid Access Token\n',
'access_Token=${accessToken}',
'App_Proof=${AppSecretProof}',data.error);
res.status(400).send(data);
}
else
{
admin.auth().createCustomToken(data.id)
.then(CustomToken => res.status(200).send(CustomToken))
.catch(error => {
console.error('Create Custom Token Failed.',error);
res.status(400).send(error);
})
}
})
})
After using command-firebase deploy I got this
> G:\New folder\firebase_functions>firebase deploy
=== Deploying to 'eatitv2-8aa15'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions# lint G:\New folder\firebase_functions\functions
> eslint .
G:\New folder\firebase_functions\functions\index.js
19:9 error Parsing error: Shorthand property assignments are valid only in destructuring patterns
✖ 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint 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! C:\Users\Maaz Farooq\AppData\Roaming\npm-cache\_logs\2020-07-18T16_58_24_083Z-debug.log
events.js:292
throw er; // Unhandled 'error' event
^
Error: spawn npm --prefix "%RESOURCE_DIR%" run lint ENOENT
at notFoundError (C:\Users\Maaz Farooq\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:6:26)
at verifyENOENT (C:\Users\Maaz Farooq\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:40:16)
at ChildProcess.cp.emit (C:\Users\Maaz Farooq\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:27:25)
at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
Emitted 'error' event on ChildProcess instance at:
at ChildProcess.cp.emit (C:\Users\Maaz Farooq\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:30:37)
at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12) {
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawn npm --prefix "%RESOURCE_DIR%" run lint',
path: 'npm --prefix "%RESOURCE_DIR%" run lint',
spawnargs: []
}
Error: functions predeploy error: Command terminated with non-zero exit code1
I see many answers on stack overflow as well as on github, but nothing proceed. i have tried my best to solve it by myown also get help from online community but now posting this to all of you.
The output shows that ESLint is giving you this error message on line 19 of index.js:
19:9 error Parsing error: Shorthand property assignments are valid only in destructuring patterns
Line 19 is url= uri below:
request({
url= uri,
json:true
},(error,fbresponse,data)=>{
If you want to give values to properties in a JavaScript objects, you have to use : instead of =, just like you did with json:true.
request({
url: uri,
json:true
},(error,fbresponse,data)=>{

Rsync fails with exit code 23 only when run from Node

I am using the rsync module with Node v0.10.22. Rsync exits with code 23 (Partial transfer due to error) when run from Node, but succeeds when run from the same exact shell as the crashed Node process.
Here is the code I am using:
var r = new Rsync()
.flags('a')
.include('*.png')
.exclude('*')
.source(path.join('source/*'))
.destination('target')
.execute(function (err, code, cmd) {
if (err && code === 23) {
console.log('Exited with 23');
console.log(cmd);
}
});
The cmd that is logged is as follows:
rsync -a --include="*.png" --exclude="*" source/* target
When I execute that exact command after Node crashes in the same shell the command returns 0 (no errors, it worked).
I have looked at rsync.js where it spawns the command:
// Execute the command as a child process
var cmdProc = spawn(this.executable(), this.args(), { stdio: 'pipe' });
this.executable() returns 'rsync'. this.args() returns ['-a', '--include="*.png"', '--exclude="*", 'source/*', 'target/'].
What is going on here? Why do I get a different exit code when running from Node as opposed to running in the same shell as where I run Node?
Edit: I set the permissions on each directory to be 777 and I am still getting the same error.
The glob in the source isn't expanded, so rsync tries to find a file named * in the source directory. Change the source to source/.

Categories

Resources