Giter Club home page Giter Club logo

node-cmd's Introduction

node-cmd

Sponsor RIAEvangelist to help development of node-cmd

Node.js commandline/terminal interface.

Simple commandline, terminal, or shell interface to allow you to run cli or bash style commands as if you were in the terminal.

Run commands asynchronously, and if needed can get the output as a string.

NPM Stats

npm info :
NPM
See npm trends and stats for node-cmd
node-cmd npm version supported node version for node-cmd total npm downloads for node-cmd monthly npm downloads for node-cmd npm licence for node-cmd

RIAEvangelist

GitHub info :
node-cmd GitHub Release GitHub license node-cmd license open issues for node-cmd on GitHub

Package details websites :

This work is licenced via the MIT Licence.

Methods

method arguments functionality returns
run command, callback runs a command asynchronously args for callback err,data,stderr
runSync command runs a command synchronously obj {err,data,stderr}

Examples

//*nix

    var cmd=require('node-cmd');

//*nix supports multiline commands
    
    cmd.runSync('touch ./example/example.created.file');

    cmd.run(
        `cd ./example
ls`,
        function(err, data, stderr){
            console.log('examples dir now contains the example file along with : ',data)
        }
    );
//Windows

    var cmd=require('node-cmd');

//Windows multiline commands are not guaranteed to work try condensing to a single line.
    
    const syncDir=cmd.runSync('cd ./example & dir');

    console.log(`
    
        Sync Err ${syncDir.err}
        
        Sync stderr:  ${syncDir.stderr}

        Sync Data ${syncDir.data}
    
    `);

    cmd.run(`dir`,
        function(err, data, stderr){
            console.log('the node-cmd dir contains : ',data)
        }
    );
//clone this repo!

    var cmd=require('node-cmd');
    
    const syncClone=cmd.runSync('git clone https://github.com/RIAEvangelist/node-cmd.git');

    console.log(syncClone);
    

Getting the CMD Process ID

    var cmd=require('node-cmd');

    var process=cmd.run('node');
    console.log(process.pid);

Running a python shell from node

const cmd=require('node-cmd');

const processRef=cmd.run('python -i');
let data_line = '';

//listen to the python terminal output
processRef.stdout.on(
  'data',
  function(data) {
    data_line += data;
    if (data_line[data_line.length-1] == '\n') {
      console.log(data_line);
    }
  }
);

const pythonTerminalInput=`primes = [2, 3, 5, 7]
for prime in primes:
    print(prime)

`;

//show what we are doing
console.log(`>>>${pythonTerminalInput}`);

//send it to the open python terminal
processRef.stdin.write(pythonTerminalInput);

Output :

>>>primes = [2, 3, 5, 7]
for prime in primes:
    print(prime)


2
3
5
7

node-cmd's People

Contributors

barrbrian avatar freemany avatar mayberex avatar riaevangelist avatar stanipetrosyan avatar stephen-last avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-cmd's Issues

How do I run command with admin ?

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!

Promise API?

Just a question:

Does this package supports async/wait flavour?

how to kill a node-cmd process ?

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')

Output from get not displaying what outputs from the terminal

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.

CD doesnt change directory

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?

async await example?

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?

Example Error?

Sync stderr: ${syncDir.stderr} → Sync stderr: ${syncData.stderr}

Console output is coming as null

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.

Not Calling Function Callback

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');
}`

How to use this to open an exe (Which is a CLI tool) and then fire commands

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

Can I interact with a CLI?

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?

returns data missing

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.

Get cmd's response in error condition

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?

How do I execute multiple commands in the same context?

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();

});

Question interfacing the console

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

getting data but also an error

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.

Does Node-Cmd the console close?

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?

Error changing the LAN Proxy Settings in on Windows 7

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

answering to a CMD y/n prompt

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

image

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

Slient fail

When I have errors in my script, the command line just fail without output any message.
Is it a normal behavior?

Running cmd.get generates maxBuffer limit error

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?

How to execute commands with ZSH environment

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)
        }

Unable to change directory.

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.

compgen -c is the only command that does not produce output

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.

Can we run command as adminstrator

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 ?

cf commands not working

  1. This Works Fine
    cmd.get(
    cf, function(data){
    console.log('\nSome Data:\n\n' + data)
    });
  2. This Doesn't work
    cmd.get(
    cf login, function(data){
    console.log('\nSome Data:\n\n' + data)
    });

Please let me know if I'm doing something wrong.

run command

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!

why will my command not execute?

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 to get stderr when using promises

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 ?

Add options to exec

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.

Real-time command

Some commands (like sudo apt update) print their outputs real-time. How can I read them whenever a new line is appended?!

Thanks!

Sudo

How would you go about running commands that require sudo access?

The second command not getting executed in Windows

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?

Add get process by Id

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>)

How to open an Excel file ?

Hello,

For my application I need to open an Excel file.
How can I open an excel file with your code ?

Thank you !
Mathieu

Getting stdout streaming

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?

Silence log output?

Is it possible to stop node-cmd from outputting the scripts that it runs? Thanks

Err first standard

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..?

Multi-line commands not working

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..?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.