Permission denied while using child_procees.exec firebase functions - node.js

I'm trying to execute a binary file of cpdf in my firebase function using the nodejs native child_procees.exec() In local tests works fine, but when I deploy my function I get this error in the logs:
Error: Command failed: /user_code/cpdf -pages file.pdf
/bin/sh: 1: /user_code/cpdf: Permission denied
There is a way to give that permissions?
Here is my code:
const exec = require('child_process').exec
var executablePath = path.join(__dirname,'/cpdf')//<-my binary file compiled for linux 32 bits
var filePathIn = path.join(os.tmpdir(),'/file.pdf')
exec(`${executablePath} ${filePathIn} -pages`,
function(error, stdout, stderr) {
if (error !== null){
console.log('error',error)
}else{
console.log('ok',stdout)
}
})
Thank you in advance

You need read- and executable permissions
sudo chmod 755 /user_code/cpdf
or
sudo chmod -RX /user_code/cpdf

Finally I've found a solution. The fact is that the node_modules folder has execution permissions, so I've added in my package.json an npm repo for node-cpdf that contain the necessary binaries and then using it's routes to the executable. Here is my code updated:
const exec = require('child_process').exec
var executablePath = path.join(__dirname,'node_modules/cpdf-n/bin/cpdf-linux-64')
var filePathIn = path.join(os.tmpdir(),'/file.pdf')
exec(`${executablePath} -pages ${filePathIn}`,
function(error, stdout, stderr) {
if (error !== null){
console.log('error',error)
}else{
console.log('ok',stdout)
}
})

Related

How to specify folder location using `cd` command inside exec function?

Instead of specifying root of file for execution in a remote server, how we can use cd command in exec() in nodejs.What i am done is like this.
var command_part1 = `ssh -p 22 root#ip`;
var command_part2 = `python3 test.py ${input}`;
var folderPath = `/root/folder/`;
var child = exec(`${command_part1} && cd ${folderPath} && ${command_part2}` , function (error, stdout, stderr) {
if (error !== null) {
callback(error)
} else {
callback();
}
});
But this code is not working, when i am executing this command locally,ssh login only is happening, further commands are not working.How can i make this working ? I dont want to specify the folder path like python3 /root/folder/test.py ${input};
Thank You Inadvance
Try this code,
`var command = `sshpass -p givePassword ssh -o "StrictHostKeyChecking no" root#ip "cd ${folderPath} && ${command_part2}"`
sshpass is a simple and lightweight command line tool that enables us to provide password (non-interactive password authentication) to the command prompt itself, so that automated shell scripts can be executed

Changing command prompt directory from Node.js script

I'm trying to change the directory of terminal using with Node.js program but not able to achieve it. Script is run as node app.js dir_name so first I'm creating the directory and then trying to change into that directory using cd command. Directory is created but the directory for terminal is not changed.
#!/usr/bin/env node
var platform = process.platform;
var figlet = require('figlet');
var chalk = require('chalk');
if(process.argv.length < 3){
console.log(
chalk.green(
figlet.textSync('mdcd', { horizontalLayout: 'full' })
)
);
console.log(chalk.red("Please provide a directory name"));
}else{
if(platform.includes("win")){
//console.log("Its Windows");
}else {
var exec = require('child_process').exec;
var command_1 = "mkdir "+process.argv[2];
var command_2 = "cd "+process.cwd()+"/"+process.argv[2];
exec(command_1, function (error, stdout, stderr) {
if(error){
console.log("Something bad happened"+error);
}else {
exec(command_2, function (error, stdout, stderr) {
if(error){
console.log("Something bad happened"+error);
}
});
}
});
}
}
command prompt directory from Node.js script
You cannot change the command prompt directory. Basically you have the process tree:
cmd / term
| -> NodeJs
You shouldn't change the working dir for cmd. However there are command you can execute to change the working dir of any process e.g. https://unix.stackexchange.com/a/282009
More
You can however change the the working dir for the nodejs process (which is what I suspect you want to do) using process.chdir https://nodejs.org/api/process.html#process_process_chdir_directory

How to run shell script file using nodejs?

I need to run a shell script file using nodeJS that executes a set of Cassandra DB commands. Can anybody please help me on this.
inside db.sh file:
create keyspace dummy with replication = {'class':'SimpleStrategy','replication_factor':3}
create table dummy (userhandle text, email text primary key , name text,profilepic)
You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.
hi.sh
echo "Hi There!"
node_program.js
const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
Here, when I run the nodejs file, it will execute the shell file and the output would be:
Run
node node_program.js
output
Hi There!
You can execute any script just by mentioning the shell command or shell script in exec callback.
You can execute any shell command using the shelljs module
const shell = require('shelljs')
shell.exec('./path_to_your_file')
you can go:
var cp = require('child_process');
and then:
cp.exec('./myScript.sh', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a command in your $SHELL.
Or go
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a file WITHOUT a shell.
Or go
cp.execFile();
which is the same as cp.exec() but doesn't look in the $PATH.
You can also go
cp.fork('myJS.js', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a javascript file with node.js, but in a child process (for big programs).
EDIT
You might also have to access stdin and stdout with event listeners. e.g.:
var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
// handle stdout as `data`
});
Also, you can use shelljs plugin.
It's easy and it's cross-platform.
Install command:
npm install [-g] shelljs
What is shellJS
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix
shell commands on top of the Node.js API. You can use it to eliminate
your shell script's dependency on Unix while still keeping its
familiar and powerful commands. You can also install it globally so
you can run it from outside Node projects - say goodbye to those
gnarly Bash scripts!
An example of how it works:
var shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Also, you can use from the command line:
$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo

Trying to exec svn ls command in a nodejs child process returning error

I want to run an svn ls <path> command when I try it out I get an error stating
svn: '.' is not a working copy
svn: Can't open file '.svn/entries': No such file or directory
which is the standard error you would get for trying to run the command without a path and in a directory that is not version controlled by SVN. But the thing is when I console.log my command before executing it it specifically states the full, valid, path to a remote SVN repository.
e.g., svn ls https://svn.example.com/this/is/a/valid/repo
If I copy and paste the log into my own bash it lists the directory just fine.
Here's the code I'm tyring to execute
function svnls (path) {
var cp = require('child_process'),
command = 'svn ls ' + path;
console.log(command); // -> svn ls https://svn.example.com/this/is/a/valid/repo
cp.exec(command, function (err, stdout, stderr) {
console.log(stderr);
});
}
Alternatively I've tried the more verbose method of spawning a bash instance:
function svnls (path) {
var bash = require('child_process').spawn('bash');
bash.stdout.on('data', function (data) {
var buff = new Buffer(data),
result = buff.toString('utf8');
console.log(result);
});
bash.stderr.on('data', function (data) {
var buff = new Buffer(data),
error = buff.toString('utf8');
console.log(error);
});
bash.on('exit', function (code) {
console.log(code);
});
bash.stdin.write('svn ls ' + path);
bash.stdin.end();
}
and it outputs the same error to console as well as the exit code (1).
Does anyone know why this is failing?

child_process exec returning a mysterious error

I have the following code (copied from the node docs apart from the command itself) :
var util = require('util'),
exec = require('child_process').exec,
child,
command = 'libreoffice --headless -convert-to pdf mysourcefile.doc -outdir /tmp';
child = exec(command,
function (error, stdout, stderr) {
if (error !== null) {
console.log(error);
return;
}
);
The command appears to be executing fine (output file is there) but error is always "Error: Command failed:" and err is not defined (the docs say err.code will give more information).
What am I doing wrong / overlooking?
It should be error.code.
The docs mix the use of error and err; it refers to the Error object provided to the callback.
like i say . years after. i got the same error. just find what can be the error - checkout (https://stackoverflow.com/a/21137820/1211174). if you are on windows there is a chance that you have someauto run on cmd. and then this autorun failed. and you get both output. sterr and stdout

Resources