JS String not behaving as expected - javascript

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'

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.

Nodejs - Get environment variables of running process

I am writing an extension for vscode, and I need to get the environment variables of a process that is already running. But I wasn't able to find a way to do it.
I know how to do it in python using psutil:
for proc in psutil.process_iter(attrs=['name', 'exe']):
if proc.info['name'].lower() == 'SomeProcess.exe'.lower():
return proc.environ()
Is there something similar for javascript/nodejs?
You can use child_process module to spawn a terminal and execute the following commands wrt platform and get the variables, parse & use or write a native node module to access the proper APIs of each platform and get the output.
Windows (Using powershell, 2019 is the PID )
(Get-Process -id 2019).StartInfo.EnvironmentVariables
Linux
tr '\0' '\n' < /proc/2019/environ
Mac
ps eww -o command 2019 | tr ' ' '\n'
Thanks to https://serverfault.com/a/66366 & https://stackoverflow.com/a/28193753/12167785 & https://apple.stackexchange.com/a/254253 &
https://stackoverflow.com/a/11547409/12167785 &
https://stackoverflow.com/a/18765553/12167785
Combining with #SudhakarRS's answer:
var child = require('child_process').execFile('powershell', [
'(Get-Process SomeProcess).StartInfo.EnvironmentVariables'
], function(err, stdout, stderr) {
console.log(stdout);
});
If you want to debug it, make sure you peek at err and stderr.
Replacing SomeProcess with notepad works for me, but using notepad.exe does not.
On powershell you can get the processes with a particular name using Get-Process [process name].
So, for example, if I have 4 instances of notepad running and do Get-Process notepad, I see this:
You can get the process IDs with (Get-Process notepad).Id which returns:
You could use the same code to choose the ID:
var child = require('child_process').execFile(
'powershell',
['(Get-Process notepad).Id'],
function(err, stdout, stderr) {
var ids = stdout.split("\r\n");
ids.pop(); //remove the blank string at the end
console.log(ids);
}
);
^ which returns:
If you just want to grab the first process with a name, it's:
(Get-Process notepad)[0].StartInfo.EnvironmentVariables
^ obviously replace notepad with your process name.
Easyish way(from here, you can use something like shelljs then run:
ps faux | grep 'PROCESS_NAME'
Then extract the process id(I'm just working on a regex) and then do:
cat /proc/THE_PROCESS/environ | tr '\0' '\n'
You'll get the the env vars back as a string something like:
THEVAR=1
ANOTHERVAR=2
I reckon you just split the string by '\n' but I'm checking!
I'll update this once I figure the regex. **Are you on linux/mac or windows?
UPDATE: Check https://github.com/shelljs/shx for cross platform
There is no builtin way to do that in javascript/nodejs. If you really need to do it, then the best way is to run a command in the terminal and then parse the output to construct the object that you need.
yep:
process.env will give you what you need :)
you can read some more here.
EDIT: it will give you environment variables only for the process you're in... did I misunderstood and you want varibales of another process?

file not found in node js (Intellij)

I am using node js express. I am trying to access a text file located in the same directory of that js file. So the file structure goes like this
- ProjectFolder
|
- many modules and folders
- routes
|
- Index.js
- input.txt
The Simple code that i have tried is ,
var data = fs.readFile('~/IdeaProjects/Title/routes/input.txt');
console.log("Synchronous read: " + data.toString());
console.log("Program Ended");
I did try different paths but nothing works. for your information, I am using fedora as os.
The error i got was,
Error: ENOENT: no such file or directory, open '~/IdeaProjects/Title/routes/input.txt'
at Error (native)
Any suggestion about how to access that file so that i can both read and write the contents of the file , will be welcomed. Looking for detailed answer.
Node doesn't interpret some characters that have special meaning like ~ or shell variables like $HOME, so you will need to use something like path.resolve() to get an absolute path or use a relative path (e.g. IdeaProjects/Title/routes/input.txt).
Also, as #Gothdo pointed out, there is a discrepency in the filename which will cause issues on case-sensitive file systems.
You will also need to either change fs.readFile() to fs.readFileSync() or add a callback to fs.readFile() like so:
fs.readFile('~/IdeaProjects/Title/routes/input.txt', function(err, data) {
if (err) throw err;
console.log("Synchronous read: " + data.toString());
console.log("Program Ended");
});

fs.readfile error claiming "no such file" for filepath that does exist

I'm trying to verify if a file exists using fs.readFile. However, I am getting an error telling me a URL that definitely exists does not exist.
Here is the error in the console and the path open in windows explorer on my machine: http://i.imgur.com/cC9bSnL.png
Here is my code:
fs.readFile(url, "utf8", function (error, data) {
if (error){
//saveContentError(url);
throw error;
}
});
message: "ENOENT: no such file or directory, open 'C:\Users\my-name\AppData\Roaming\Company%20Name\DashboardApps\Apps\eCatalog\Contents\Product Groups\order.csv'"
path: "C:\Users\my-name\AppData\Roaming\Company%20Name\DashboardApps\Apps\eCatalog\Contents\Product Groups\order.csv"
I also tried changing url to url = url.replace(' ', '%20')
This is from my app.js which has a different root than my node folder. Initially this was an issue as I was only passing the end of the path and it was adding it to the wrong root. However since I'm passing it the full path now (starting with C:) I assumed this would correct that issue.
Does anyone know why I'm being told that no file exists when in reality it does?
Thank you very much for your time. Let me know if I am being unclear or if you need more information.
Instead of creating a path using \, either use /, or \\. The latter because \ is an escape character, which needs to be escaped before using it -> \\ to use \
For instance \n is the newline character... So you are sending strange requests, instead of a correct path...

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

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.

Categories

Resources