riaevangelist / node-cmd Goto Github PK
View Code? Open in Web Editor NEWSimple commandline interface to allow you to run cli or bash style commands as if you were in the terminal.
License: MIT License
Simple commandline interface to allow you to run cli or bash style commands as if you were in the terminal.
License: MIT License
cf
, function(data){cf login
, function(data){Please let me know if I'm doing something wrong.
hello
i was using this library and its quite good
but unfortunately the command im using prompts me to accept or deny via y/n
i was wondering if the library allows me to answer to this prompt
if it is possible can you provide me with a sample code ,all i found is retrieving the process id
is there a way to reconnect and answer y to the process ?
i already tried this
const syncDir=cmd.run('cd ../tools/ && ffmpeg -i input.mkv -t 10 test3.mkv' ,function(err, data, stderr){ console.log('running'); console.log('data ',data); console.log('stderr ',stderr); console.log('err ',err); if ( stderr.includes('already exists. Overwrite ? [y/N]')) { data.stdin.write("y"); console.log('accepting '); } });
but i couldn't make it work
if its not possible i can work around it but i wanted to check with you guys beforehand
Hello,
I tried using this package for running some command line commands. The command are running as far as I can tell because I see the task is done but I am unable to see the output which is printed as null.
var testNodeCmd = function(){ cmd.get( 'dir', function(data,err,stderr){ console.log(data); } ); }
testNodeCmd();
The output for this is coming as null.
I was wondering if there was a way I can use this to interact with a CLI (Heroku CLI)? Here's what I'd like to do:
cmd.get(
'heroku pg:psql --app fo3-staging', //if I run this from terminal it will return the psql CLI
function(data, err) {
if (!err) {
cmd.run(query); //this should run on the psql CLI
} else {
console.log('error', err);
}
}
);
If I run heroku pg:psql --app fo3-staging from terminal it returns the psql CLI and I can then issue commands, however, when I run it via node-cmd the psql CLI never comes up.
Any thoughts?
Hello,
For my application I need to open an Excel file.
How can I open an excel file with your code ?
Thank you !
Mathieu
I write my code like
cmd.get(
'ipconfig',
function(err,data){
if(err) throw err;
console.log('the output of ipconfig is : ',data)
}
);
But the encoding of data is incorrect because the default encoding of exec is utf-8, and on some platform like a Chinese version of Windows, the output of command execution is cp936, then the final output is filled with incorrect characters.
However, I can do it with passing extra options to exec to make it work.
const iconv = require('iconv-lite');
const { exec } = require('child_process');
exec('ipconfig', { encoding: 'buffer' }, (error, stdout) => {
console.log('the output of ipconfig is : ',iconv.decode(stdout, 'cp936'));
});
So hope to add options to the underlying exec call.
I am not sure, but may this be a bug?
I have a very simple script:
function testingStrangeThing(promObj) {
return new Promise((resolve, reject) => {
try {
cmd.get(
'ls',
function(error, data, stderr) {
if(error) {
console.log("error first"); console.log(error);
console.log('');
console.log('data'); console.log(data);
console.log('');
console.log('stderr'); console.log(stderr);
reject(error)
}
else if(data) {
console.log("God data");
resolve(data);
}
else {
throw 'No error and no data as response of gdallocationinfo';
}
}
);} catch(error) { reject(error); }
});
};
It logs the content of the current directory correctly, but also writes this error:
error first
{ Error: Command failed: ls
at ChildProcess.exithandler (child_process.js:272:12)
at ChildProcess.emit (events.js:159:13)
at maybeClose (internal/child_process.js:943:16)
at Socket.stream.socket.on (internal/child_process.js:363:11)
at Socket.emit (events.js:159:13)
at Socket.ReaddirReadable.destroy (/home/n_trza01/Geosoft2DiscoveryService/node_modules/fs-readdir/index.js:159:8)
at Socket.onSocketFinish (net.js:279:17)
at Socket.emit (events.js:164:20)
at finishMaybe (_stream_writable.js:605:14)
at endWritable (_stream_writable.js:613:3) killed: false, code: null, signal: null, cmd: 'ls' }
I am using node.js version 9.2.1.
In my node app I need to run command as admin
And I tried to run my node app as admin but it`s not working
Is there a way I can run command as admin ?
Thanks!
I have these lines of codes:
var dir = '/var/www/html/superprojectexperimental/' + projectName;
cmd.run('mkdir -p '+ dir);
cmd.run('cd ' + dir);
cmd.get('pwd',function(data){
console.log('the current working dir is : ',data);
}
);
The data
printed is only /
The mkdir -p
works pretty well.
I worked with git through this module, but unfortanetely I can't change the directory or to create the file.
var cmd=require('node-cmd');
var readline = require('readline');
var repository;
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Enter adress: ", function(address) {
repository = address.slice(address.lastIndexOf('/')+1, address.length);
cmd.run('git clone '+ address);
console.log(repository); //here starts the probem
cmd.run('cd ' + repository);
cmd.run('git log');
cmd.run('dir');
console.log('ok'); // ok works
rl.close();
});
Hi, I am very new to this, so a have a question:
can I run a var cmdS = "ren file1.xlsm file2.xlsm" command which I saved as a string? I thought I could do it just like this:
cmd.run(cmdS);
the file i want to rename is in the same folder as my node.js file
Thanks!
I have tried the following code:
const cmd = require('node-cmd');
let directory = "C:\\Lance\\devhub\\UkWorkflow";
cmd.get(
`cd ${directory}
sfdx force:source:convert -d outputTmp/ --json`,
function(err, data, stderr) {
if(!err) {
console.log("data is: ");
console.log(data);
} else {
console.log("Error!");
console.log(stderr);
}
}
);
It seems to me that second command - sfdx not getting executed at all. Any ideas about why this is happening?
When I have errors in my script, the command line just fail without output any message.
Is it a normal behavior?
It would be cool if we could directly access any process by a command like
const processRef = cmd.getProcessById(<processid>)
or
const processRef = cmd.getProcessByTitle(<process_title>)
const cmd = require('node-cmd');
cmd.run('start node c:\Trader\Logic\ok.js');
it opens a new cmd window and shuts it immediately.
content of ok.js is an interval every second to log "ok", so it's not like the new cmd window gets closed because the js is finished.
running 'start node c:\Trader\Logic\ok.js' in cmd does what it's supposed to do.
Any idea why it won't work from javascript?
How would you go about running commands that require sudo access?
Is it possible to stop node-cmd from outputting the scripts that it runs? Thanks
Hello, today when I use the 'qrsctl' tool, I use a cmd command: "qrsctl listprefix bucktname '' ", it should return:
' market:
Aaaaa
Bbbbb '
But the data in the script returns only:
'market:
'
I make sure that the execution is correct when executed on the command line. I could not understand.
I have a set of code that the callback doesn't get called on and I suspect it is because of NMCLI using the host of my docker containers DBUS connection.
` cmdTextFinal = 'export DBUS_SYSTEM_BUS_ADDRESS=unix:path=/host/run/dbus/system_bus_socket\n' + cmdText.join('\n');
console.log(cmdTextFinal);
cmd.get(cmdTextFinal), function(err, data, stderr){
if (!err) {
console.log('Applied Settings for Network');
} else {
console.log('Error: ' + err);
}
console.log('I ran');
}`
I have the following question, after running cmd.runSync(), for example, does node-cmd close the console it was working with after executing the function?
I'm trying to cancel running a node-cmd invoked script ....
but the script keeps running after I tried :
process.kill(nodecmdProcess.pid, 'SIGKILL')
and :
nodecmdProcess.kill('SIGKILL')
This might be causing node-cmd is unable to open a node file. Maybe?
Some commands (like sudo apt update
) print their outputs real-time. How can I read them whenever a new line is appended?!
Thanks!
I have a scenario in my mobile automation framework (Typescript based) wherein I have to open an exe which is a command line interface tool and then type the commands
This CLI basically connects to a USB device. I fire commands to get certain values from the connected USB device (Example USB_HID_GetType which returns the HID)
I want to chain the commands of opening this exe and firing a command to get some value from the connected USB.
@RIAEvangelist any thoughts or inputs
I am using the bluebird library to use promises, and I have to CD to a certain directory and then run a command. I am using getAsync like this:
var cmd = require('node-cmd');
var Promise = require('bluebird');
const getAsync = Promise.promisify(cmd.get, { multiArgs: true, context: cmd });
getAsync('cd C:\\Program Files (x86)\\CouchDB Telemetry Integrator') //change directories (FAILS)
.then(function(){
console.log("Changed Directory to \\CouchDB Telemetry Integrator ");
})
.then(function(){ // lists directory contents
getAsync(
'dir',
function(err, data, stderr){
console.log('the current dir contains these files :\n\n',data)
}
)
})
.catch(function(err){
console.log(err);
});
The problem is that when I list the dir contents it actually shows that I am in my root folder and did not change directories. Why is this happening?
Just a question:
Does this package supports async/wait flavour?
I have a simple script I'm running that performs some pre-deploy tasks, and then deploys my built to Elastic Beanstalk on AWS.
var cmd = require('node-cmd');
var util = require('gulp-util');
var env = util.env.MY_FLAG;
console.log("Running script");
try {
cmd.get(
`gulp MY_GULP_COMMAND --MY_FLAG ${MY_FLAG}`,
results => {
console.log(results);
cmd.get(
`eb deploy MY_EB_ENVIRONMENT`,
results => { console.log(results); }
)
}
);
} catch (e) {
console.log(JSON.stringify(e))
}
This is the output of running my script:
Running script
null
{ Error: Command failed: eb deploy MY_EB_ENVIRONMENT
at ChildProcess.exithandler (child_process.js:206:12)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Socket.<anonymous> (internal/child_process.js:334:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:493:12)
killed: false,
code: 4,
signal: null,
cmd: 'eb deploy MY_EB_ENVIRONMENT' }
However, here's the output of running the commands in the terminal specifically:
gulp MY_GULP_COMMAND --MY_FLAG ${MY_FLAG}
[11:19:04] Using gulpfile MY_GULPFILE.js
[11:19:04] Starting 'MY_GULP_COMMAND'...
[11:19:04] Finished 'MY_GULP_COMMAND' after 64 ms
eb deploy MY_EB_ENVIRONMENT
Creating application version archive "APP_ARCHIVE".
Uploading: [##################################################] 100% Done...
ERROR: ServiceError - You cannot have more than 1000 Application Versions. Either remove some Application Versions or request a limit increase.
For some reason, no output at all is being displayed from the gulp command, and not the correct output from the eb deploy command. Here I was experiencing a deploy error and couldn't really tell what it was without having to run the commands myself.
Hi,
I'm running a command that starts a program that prints to stdout over time.
I want to print out this output while it is happening.
if I use cmd.get() I will get the output only after the program has finished.
If I use cmd.run() I don't get any output and I have no way to know when the program finished.
how should I do that?
./node_modules/node-cmd/cmd.js Module not found: Error: Can't resolve 'child_process'
Has anyone run into this? Thanks in advance.
Sync stderr: ${syncDir.stderr} → Sync stderr: ${syncData.stderr}
like the issues title
I tried executing a cmd.get command and i get a stdOut maxBuffer exceeded error. My cmd executes a .exe file that is basically a cmd that generates output and this should be displayed on screen, but if it generates an exception, the message is quite long, so I guess that this is why I get this problem. Is there any way to modify the cmd.get method to accept a maxbuffer as optional params?
苹果笔记本上可以使npm-cmd吗?还是只能在windows上使用
Hi, I'm trying to execute several commands but instead of /bin/sh I wanted to execute with zsh environment...
I tried to use source ~/.zshrc
but without success, can someone help me over here?
var command= "textScriptInZsh"
cmd.get(`
source ~/.zshrc
${command}
`,
function(err, data, stderr){
if (!err) {
console.log('Test done...\n\n',data)
} else {
console.log('error', err)
}
Im trying to change the LAN Proxy Settings on Windows 7 through CMD from within NODE but am getting the following error.
Ive tried a few different libraries as well as use child process to run it but no luck. It works fine when I just run the command in CMD, but when running through node, I havent had any luck? ideas?
command failed reg add /? for usage - invalid key name
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyServer /t REG_SZ /d 192.168.1.1:8080 /f
*note proxy is fake in this example
Pardon my ignorance on this topic, but I am assuming that this would not handle pauses, prompts etc. in the terminal?
My objective is actually to interface with the Octave command line. Have you ever tried anything like that, Octave or other command line software?
Is this piggybacking the standard io stream?
If you find my question insulting please accept my apology and note that I intend to get off my ass and try this, just haven't the time today. :D
I am trying to get cmd's response in both success and error conditions. I am having the following code:
const cmd = require('node-cmd');
const Promise = require('bluebird');
const getAsync = Promise.promisify(cmd.get, { multiArgs: true, context: cmd });
getAsync('sfdx force:source:status --json').then(data => {
console.log('success');
console.dir(data);
}).catch(err => {
console.log('error');
console.log(err.message);
});
I am trying to get the json output in error conditions as well. However, when error happens, it is hard to retrieve that. Any idea about how to walk around this issue?
node-cmd works fine for dozens of commands, except for the 'compgen-c'
command which returns an error: stderr returns: /bin/sh: 1: compgen: not found
err returns: {"killed":false,"code":127,"signal":null,"cmd":"compgen -c"}
This is my code:
router.get('/commands', (req, res) => {
cmd.get('compgen -c',function(err, data, stderr)
{res.send(data)}
Expected output: a list of all Linux commands on my Lubuntu box.
Now, if i run 'compgen -c' in the terminal, it executes fine and outputs all 2227 Linux commands. Linux error code 127 means (as far as i know) "Command not found". The above code works flawless with other commands, like 'ls' etc.
My guess is that compgen behaves a bit different then normal commands.
For example: whereis compgen returns (terminal): empty, while it is expected to return the location of the binary.
My question is: how to get the output of compgen -c into my node script? My goal is to have a list of all Linux commands.
I see you have an example using multiple lines, which looks really useful.
cmd.get(
`
git clone https://github.com/RIAEvangelist/node-cmd.git
cd node-cmd
ls
`, function(data, err, stderr){}
)
I can't seem to get this to work:
// works!
cmd.get(`node -v`, function (data, err, stderr) {
if (err) {
console.log('cmd err ===', err)
} else {
if (stderr) { console.log('cmd stderr ===', stderr) }
console.log('cmd data ===', data) // cmd data === v4.2.2
}
})
// doesn't work!!
cmd.get(`
node -v
`, function (data, err, stderr) {
if (err) {
console.log('cmd err ===', err)
} else {
if (stderr) { console.log('cmd stderr ===', stderr) }
console.log('cmd data ===', data) // cmd data ===
}
})
I'm not getting any errors (from err
or stderr
), but data
is an empty string as soon as I make the template string multi-line.
What am I doing wrong..?
Hi, first of all this package is great and very straightforward but I have a question. How do I use the async / await
functionality with this package?
Hey, I'm having an issue debugging failing commands.
I'm using Bluebird to promisify cmd.get()
(as suggested in the examples) but it seems that the "multiArgs" param only cares about when the promise resolves without errors.
I can't see to be able to get "stderr" from the catch()
method which would be super useful to see what actually failed.
Is it something that can be done ?
how to run command with stdin and callback
I had run this script "net share Docs=C:\ProgramData\DesktopAlert /grant:everyone,FULL"
But this script required to run by adminstrator cmd
Do you have any options for this ?
Which option let you change direction from which you are running the command?
I'd like to use Bluebirds Promise.promisify
.
import Promise from 'bluebird'
import cmd from 'node-cmd'
const getAsync = Promise.promisify(cmd.get, { multiArgs: true, context: cmd })
getAsync('node -v').then(data => {
console.log('cmd data', data)
}).catch(err => {
console.log('cmd err', err)
})
This fails I think, because node-cmd
doesn't use the standard node error-first pattern which Bluebird wants:
The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument.
The above code calls catch
but actually displays the contents of data
.
Any plans to switch to standard node-style error-first callbacks..?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.