nodejs 'exec' command doesn't execute 'sed' command properly - javascript

I have a file where I want to scan it, find the character '{' and create a new line, then add an IP on the new line and add a semi-cologne to the end of the line, then write to a config file.
I can accomplish this with the following sed command when running from shell:
sed -i 's/{/&\n1.1.1.1;/g' /tmp/test.conf
inside test.conf:
acl testACL{
};
the output from the command in shell shows:
acl testACL{
1.1.1.1;
};
works perfect! Now the problem is when I get nodejs to execute it:
var sys = require('sys');
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) };
exec("sed -i 's/{/&\n1.1.1.1;/g' /tmp/test.conf",puts);
return 0;
when I run the command in console: 'nodejs test.js'
I get blank output and when I check the file, the file 'test.conf' has not been altered! why?!
Also if you're thinking 'its a permissions issue!' I've had nodejs exec command write basic echos to the test config file and it worked fine.
I have also tried the 'shelljs' module with no luck there. I have tried countless combinations for hours now with no prevail! I'm puzzled.

I think you need to escape your \n as \\n. Right now, it's getting parsed as a literal newline in the command, which is messing it up.

Related

Node.js run command line (child_process?)

I have a Node.js program where I need to, on a button click, run 2 commands in the Windows command line. For example, the process I'm trying to automate by the button click would be doable manually by going to cmd and entering the following commands:
pushd \\myserver.com\folder1\folder2 //Connect to remote server folder structure
mkdir NewFolder //Create new folder in the remote folder
I've found many resources pointing that I should use 'child_process', but I'm absolutely lost when it comes to shell scripting and am having a really hard time figuring out how to do this. Here's the code I have so far:
var cp = require('child_process');
cp.exec('pushd \\\\myserver.com\\folder1\\folder2\\', { shell: '/bin/bash' }, function(err, stdout, stderr){
if(err){
console.log(err);
}
});
But this above code just returns this error (which oddly removes the '\'s from the given dir):
{ Error: Command failed: pushd \\myserver.com\folder1\folder2\
/bin/bash: line 1: pushd: \myserver.comfolder1folder2: No such file or directory
at ChildProcess.exithandler (child_process.js:281:12)
killed: false,
code: 1,
signal: null,
cmd: 'pushd \\\\myserver.com\\folder1\\folder2\\' }
/bin/bash: line 1: pushd: \myserver.comfolder1folder2: No such file or directory
I'm really lost here and would appreciate any help. Any alternative you have to child_process may also be very helpful. Thank you!
Usually all the escape sequences used for string uses '\\' for a single backslash. It is understandable you used it here for the directory path for windows.
In JS particularly '\\' doesn't exactly work like that
'abc\
def' == 'abcdef' // true
'\a' == 'a' // true
When a '\' is not followed by a character with any special meaning, it is considered to be a LineContinuation instead.
As you can see from your error output using '\\\\myserver.com' considered '\myserver.com'. Plain workaround is to use '\\\\' for single '\' or use '/' for path separation which I'm not pretty sure if shell will execute it.
This is one of the blogs explains about it in details Link.
The shell is incorrect here:
{ shell: '/bin/bash' }
It should be:
{ shell: 'CMD.EXE' }
Because in the beginning of your post, you tell that you run 2 commands in the Windows command line, which indicates you are not using Bash, which is (usually) not installed on Windows.

How to run complex command in node js spawn?

I am developing a lib for docker command line in nodejs, I am still in starting face, I just tried basic docker run command using spawn in node js - everything works fine but it's not working for complex cases like the one below.
I want to run docker run --rm -it julia:0.3.6 julia -E "[x^2 for x in 1:100]" in nodejs, but I am gettting below error -
the input device is not a TTY
Docker Shell existed with status = 1
Below Code -
const
spawn = require('child_process').spawn,
dockerDeamon = spawn("docker", ["run","--rm", "-it", "julia:0.3.6", "-E", "\" [x^2 for x in 1:100]\""] );
dockerDeamon.stdout.on('data', data => {
console.log(`${data}`);
});
dockerDeamon.stderr.on('data', data => {
console.log(`${data}`);
});
dockerDeamon.on('close', code => {
console.log(`Docker Shell existed with status = ${code}`);
});
Is there any better way to execute the above script ?
You're passing the -t (--tty) flag to Docker, which tells it that it should expect the input and output to be attached to a terminal (TTY). However, when you're using spawn, you're instead attaching it to a Node.js stream in your program. Docker notices this and therefore gives the error Input device is not a TTY. Therefore, you shouldn't be using the -t flag in this case.
Also, note that you don't need nested quotes in your last argument, "\" [x^2 for x in 1:100]\"". The purpose of the quotes is to preserve the spaces and other special characters in the argument when running in a shell, but when you use spawn you're not using a shell.
So your statement should be something like:
dockerDeamon = spawn("docker", ["run","--rm", "-i", "julia:0.3.6", "julia", "-E", "[x^2 for x in 1:100]"] );

JS String not behaving as expected

I am creating file paths like so:
'/Users/User/Documents/dev/engineerappcopy/VGimages/'+deviceName+'.png'
these file paths are passed to a function as parameters, this function uses the file path to perform a command on the terminal.
However, this string seems to split into 2 parts when used by the function. presenting this error:
exec error: Error: Command failed: /bin/sh -c adb pull /sdcard/nexLogin.png /Users/User/Documents/dev/engineerappcopy/VGimages/josh
.png
/bin/sh: line 1: .png: command not found
this is because '.png' has been separated from the main string.
Remove the new line character from the end of the deviceName variable. You should probably use the trim method to do this.
'/Users/User/Documents/dev/engineerappcopy/VGimages/'
+ deviceName.trim()
+ '.png'

How can I get terminal size in a piped node.js process?

I'm using Grunt to kick off a unit-test framework (Intern), which ultimately pipes another node.js process that I'm then using Charm to output results to the screen. I'm having to pass in the terminal size information from a Grunt config option, but it's a bit messy and I'd like to try and get the terminal size from within the piped process, but the standard process.stdout.cols/getWindowSize are simply unavailable as the piped process doesn't register as TTY (although Charm works fine with it all).
Any suggestions?
EDIT Just to be clear here ... the Grunt JavaScript file is running in the main node.js process, but the file I'm attempting to retrieve this info from (and where I'm therefore running people's suggested commands) is in a spawned child process.
Try these:
tput cols tells you the number of columns.
tput lines tells you the number of rows.
echo -e "lines\ncols"|tput -S to get both the lines and cols
There's stty, from coreutils:
$ stty size #60 120 <= sample output
While running the below code in terminal prints the cols:
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("tput cols", puts);
The pty.js module can make a child act like a regular terminal.
var pty = require('pty.js');
var term = pty.spawn('bash', [], {
name: 'xterm-color',
cwd: process.env.HOME,
env: process.env
});
term.on('data', function(data) {
console.log(data);
});
term.write('ls\r');
term.resize(100, 40);
term.write('ls /\r');
console.log(term.process);

Parsing of strings containing forward slash in node.js command line

Hi I am writing a node js app where I need to pass the path to some file via command line. I need to do this for configuration purposes. I understand that I can put all config details in a json file and then load it inside the app. But this is a specific requirement.
Here is my code
app.js
----
-----
console.log(process.argv);
---
--
// Start server
Now when I run this file in node as:
node app.js hii
Output
'hii'
But if I do
node app.js '/samplePath'
I get this output in DOS:
'\'/samplePath\''
I get this output in Git Bash:
'C:/Program Files/Git/samplePath'
How will I get just '/samplePath' as output? What am I doing wrong? Any help would be appreciated.
In order to get the last item, try
process.argv[2].split(/\//).pop();
You will have to parse the command line options your self. However you can look into this node module that will make this easy for you.
npm install commander
Here is an example from their Github page
var program = require('commander');
program
.version('0.0.1')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);

Categories

Resources