I want to run the terminal command n nodejs language - node.js

Creating a Nodejs server code, I'd like to turn on a new terminal window and enter a command.
var exec = require('child_process').exec
exec('gnome.terminal', (err,out,stderr) => {
console.log(out)
});`
I'd like to open a new window with the code above and enter a command.
(new) 1 terminal -> command : roslaunch rpliadr_ros rplidar.launch
(new) 2 terminal -> command : roslaunch hector_slam_launch tutorial.launch

Please look up shell.js module.

You can use OpenTerm module. It's do exactly what you want - open terminal, and execute.
It has both functions for individual terminals: ( consider to use them only if you sure they exists in your PATH ).
const { VT } = require('open-term')
VT.linux.xterm('ls -l') // Runs "ls -l" command in xterm.
VT.linux.guake('ls -l') // Runs "ls -l" command in guake.
And configurable function which automatically determines terminal to use:
const { VTexec } = require('open-term')
VTexec('help') // "help" command works both on bash and cmd.

Related

How to correctly execute the cd command from inside of Node.js?

I'm developing a very simple Electron app for Windows which, when executed from the command prompt, opens a dialog box trough which the user can select a folder. The app would then change the command prompt directory to the directory selected by the user.
My end goal is to be able to simply type dirnav, select a folder from the dialog box and have the app take care of redirecting the command prompt to the selected directory (instead of typing cd C:\Users\myName\whateverDirectory. Here's what I have so far:
const exec = require('child_process').exec;
const electron = require('electron');
const {app, dialog} = electron;
app.on('ready', () => {
dialog.showOpenDialog(
{
title: 'Select a directory',
defaultPath: '.',
buttonLabel: 'Select',
properties: ['openDirectory']
}, (responce) => {
exec('cd ' + responce[0], () => {
app.quit();
});
}
);
});
Unfortunately, simply doing exec('cd ' + responce[0]) doesn't seem to work, because instead of changing the directory of the command prompt the application was runned from, it changes the directory of another (unknown to me) command prompt. Is there any way to work around that?
Here's a simple scheme that will work from a batch file:
for /f %%i in ('node yourapp.js') do set NEWDIR=%%i
cd %NEWDIR%
And, my yourapp.js is this (just to prove that the concept works):
process.stdout.write("subdir");
This will end up executing in the batch file:
cd subdir
You should be able to plug in your electron showOpenDialog() in your own app and then just write the result to process.stdout.
The for loop in the batch file does indeed look odd, but it's the only way I found that people have found to get the stdout from an app into an environment variable that you can then use later in the batch file. You could, of course also use a temp file (redirect output to a temp file), but I thought an environment variable was a cleaner solution.

How to run linux terminal commands on windows?

I'm not sure how to ask, but I'd like run the 'bash' command on windows 10 so that some linux commands run later. I'm using the framework Electron and the Child Process.
var os = require('os')
var exec = require('child_process').exec
if (os.platform() =='win32'){
var cmd_win = 'bash'
exec(cmd_win, function(error, stdout, stderr){
console.log(error)
});
}
The code snippet gives "Error: Command failed: bash". Does anyone know why? And can you help me? I hope you understood my question.
To initialize the WSL subsystem, you must launch a (hidden) Bash console window in the background, which doesn't work if you execute bash.exe directly - it works with neither exec nor execFile.
The trick is to get the shell (cmd) process that Node.js spawns to launch bash.exe without blocking, which, unfortunately, isn't easy to do: start cannot be used, because bash.exe is a console application and therefore makes start act synchronously.
The solution is to create an aux. VBScript file that launches bash.exe, which itself can be invoked asynchronously via wscript.exe. Note that the Bash console window is launched hidden:
var os = require('os')
var exec = require('child_process').exec
if (os.platform() === 'win32') {
var cmd_win = '\
echo WScript.CreateObject("Shell.Application").\
ShellExecute "bash", "", "", "open", 0 > %temp%\launchBashHidden.vbs \
& wscript %temp%\launchBashHidden.vbs'
exec(cmd_win, function(error, stdout, stderr){
if (error) console.error(error)
});
}
Note that the aux. VBScript file %temp%\launchBashHidden.vbs lingers between invocations. Cleaning it up after every run would require more work (you can't just delete it right away, because wscript, due to running asynchronously, may not have loaded it yet).
By default, exec will use cmd.exe to execute commands in windows. What you may be looking for is the shell option specified in the docs.
shell Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)
const os = require('os')
const exec = require('child_process').exec
if (os.platform() === 'win32') {
exec('ls', {shell: 'path/to/executable.exe'}, (err, stdout, stderr) => {
if (err) {
console.error(err)
return
}
console.log(stdout)
})
}
I have found a short way to do that that is :
Install git on your computer
Add C:\Program Files\Git\usr\bin to your path variable.
and check whether you can run linux commands in cmd.

Execute multiple commands in Third party CLI mode using Node JS

I want to execute 5 commands in a sequence and log its output.For Example. First command XXXcli ip_address (This will connect me to the third party CLI mode) and the next commands will execute a script,the next will log output etc.But my problem is when I do SSH through node.js and spawn a shell inside ssh session, when I execute the first command I couldn't see any output on my Console. The Session creates a shell and once the shell enters the third party CLI ,Its becoming impossible for me to fire the next command or log the output of the first command.Kindly help me on this. I'm stuck with this for a long time
Update:
My Code:
session.on('exec', function (accept, reject, info) {
console.log('Client wants to execute: ' + inspect(info.command));
var stream = accept();
var cp = spawn('XXXCLI 10.21.254.12', {shell: true});
stream.stdin.pipe(cp.stdin);
cp.stdout.pipe(stream.stdout);
sleep(6000);
cp.stderr.pipe(stream.stderr);
cp.on('exit', function (code, signal) {
stream.exit(signal || code);
}).on('end', function (code, signal) {
stream.close();
});
});
When I manually type the first command 'XXXCLI ip_address' in my command prompt and press enter,I will get a output "Connected to CLI...." .Once I get this connection successful, I need to execute my second command i.e "Lmc sample" which will load the master config and I will get the output as "Message sent..", third command will execute a script,will get output as "Message sent.." .This is what happens when I enter these commands manually in cmd prompt and execute.
What is happening is once I execute my first command i.e "XXXCLI 10.21.254.12" manually in cmd, The path where we actually execute the commands i.e( C:\users\CLI>) will not be visible. This happens because now it got connected with the above mentioned ip (10.21.254.12) .And Only after connecting to this ip ,I can able to execute my other commands.i.e command to load master config ,cmd to execute script etc.
So I want to execute my first command and get its stream in a variable and execute rest of the commands inside the stream created by first command
Thanks!
I fixed this using Child Process in Node.js and writing the commands in the stream directly. When I did the same with Java it didn't work, but it did in Node.js.

Prereload script into node interactive mode

Is it possibille to run node.exe, pipe a text into it, and continue the interactive session?
I want to create a shortcut bat (or bash) file for editing my database.
Usually this is what I'm doing:
$ node
>var db=require('mydb')
>db.open('myserver')
>//Now I can start access the db
>db.query...
I want to do something like that:
$ node -i perDefinedDb.js
>db.query(.... //I don't want to define the DB each time I run the node.exe
I tried some like that:
echo console.log(a) | node.exe
This is the result:
3
And the program is Finish. I want to continue the node REPL after piping something into.
In Other Words:
I want to be able to use my DB from node REPL, without defining it each time.
Launch the REPL from your js file and you can give the context you want:
const repl = require('repl');
var db = require('mydb');
db.open('myserver');
repl.start('> ').context.db = db;
Now you just have to run this file (node myREPL.js) and you can REPL as usual.

Change the command prompt on entering a command

I need to be able to change the prompt on running an executable of a c file to get a custom prompt
E.g:
$ abc
abc>
Here the user can give the commands acceptable to the program.
I saw this happen for programs like MySQL and was wondering if it is possible to do this.
You can use gnu readline for custom prompt
#include <readline/readline.h>
#include <readline/history.h>
while (1)
{
command = readline ("$abc");
command = readline ("abc>");
//validate your command name
system(command);
add_history (command); ///add command in history
}
you can include the readline library in your program to make it have a modern command line interface.
Or you can simply build a loop get each line from input and get the tokens from that line of input to execute commands, and there printout your abc> prompt.

Resources