Automatic writing text to the console using Node.js - node.js

I need to clone GitHub repository using SSH and Node.js script:
var exec = require('child_process').exec;
exec('git clone git#github.com:jquery/jquery.git',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
}
);
If github.com not in known_hosts file, SSH forcing to enter "yes" on the question "Are you sure you want to continue connecting (yes/no)?".
How can I automate the input of this text?
P.S. I know about StrictHostKeyChecking=no, but I need to clone repository without changing SSH config.

Sure, that is entirely possible. When you call child_process.exec, it actually returns a ChildProcess Object. It contains an .stdin object which is an implementation of a Writable Stream, which you can pipe to / write to. Documentation on ChildProcess.stdin, also on Writable Stream.
Here is some example code that relates to your question:
var exec = require('child_process').exec;
var cmd = exec('git clone git#github.com:jquery/jquery.git', function (error, stdout, stderr) {
// ...
});
cmd.stdin.write("yes");

You could pass in yes prior to your git clone command.
exec('yes | git clone git#github.com:jquery/jquery.git'...

Related

How to run shell script file using nodejs?

I need to run a shell script file using nodeJS that executes a set of Cassandra DB commands. Can anybody please help me on this.
inside db.sh file:
create keyspace dummy with replication = {'class':'SimpleStrategy','replication_factor':3}
create table dummy (userhandle text, email text primary key , name text,profilepic)
You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.
hi.sh
echo "Hi There!"
node_program.js
const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
Here, when I run the nodejs file, it will execute the shell file and the output would be:
Run
node node_program.js
output
Hi There!
You can execute any script just by mentioning the shell command or shell script in exec callback.
You can execute any shell command using the shelljs module
const shell = require('shelljs')
shell.exec('./path_to_your_file')
you can go:
var cp = require('child_process');
and then:
cp.exec('./myScript.sh', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a command in your $SHELL.
Or go
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a file WITHOUT a shell.
Or go
cp.execFile();
which is the same as cp.exec() but doesn't look in the $PATH.
You can also go
cp.fork('myJS.js', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a javascript file with node.js, but in a child process (for big programs).
EDIT
You might also have to access stdin and stdout with event listeners. e.g.:
var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
// handle stdout as `data`
});
Also, you can use shelljs plugin.
It's easy and it's cross-platform.
Install command:
npm install [-g] shelljs
What is shellJS
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix
shell commands on top of the Node.js API. You can use it to eliminate
your shell script's dependency on Unix while still keeping its
familiar and powerful commands. You can also install it globally so
you can run it from outside Node projects - say goodbye to those
gnarly Bash scripts!
An example of how it works:
var shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Also, you can use from the command line:
$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo

How to handle multiple async requests within a Grunt custom task?

I am working on a grunt task that installs the latest wordpress plugins from the wordpress svn repo, this is done via a command line task.
Ideally I would like this done synchronously so that I can see output as each plugin installs (via svn co) .. but it seems like exec simply executes and doesn't wait, so using var done = this.async() and done(error) works well with a single async action, but not multiple like in this case ... what am I missing?
grunt.registerTask('install-plugin', 'Get latest versions of required plugins', function(p){
var exec = require('child_process').exec;
var plugins = p ? [p] : grunt.config.get('wp_plugins');
var pattern = 'svn co http://plugins.svn.wordpress.org/%s/tags/$(curl -s http://plugins.svn.wordpress.org/%s/trunk/readme.txt | grep "Stable tag:" | sed -E "s/[Ss]table tag: *//")/ plugins/%s'
var done = this.async();
plugins.forEach(function(plugin) {
// using split/join instead of util.format('foo%s', 'bar')
var cmd = pattern.split("%s").join(plugin);
exec(cmd, function (error, stdout, stderr) {
grunt.log.writeln('Installing WordPress Plugin: "' + plugin + '"');
grunt.log.writeln(stdout);
done(error);
});
});
});
Your problem here is you are calling done (aka this.async()) each time through the loop but grunt doesn't know you have a loop. You need to have your own callback which tracks when all of the async things are done and then only once call grunt's this.async().
Alternatively, searching the web for "node exec synchronous" will turn up plenty of ways to achieve that task if it's what you want.
You are calling done before it gets stdout message. Listen on events to get notify when it is actually done... something along these lines:
exec(cmd, function (error, stdout, stderr) {
stdout.on('data', function(data){
grunt.log.writeln('Installing WordPress Plugin: "' + plugin + '"');
grunt.log.writeln(stdout);
done();
});
stderr.on('data', function(err){
done(err);
});
});

CasperJS/PhatomJS running shell commands

For the last few days I have been struggling with running shell commands from CasperJS/PhantomJS.
I am running simple unix sed on a file in node, which runs just fine:
var sys = require('sys')
var exec = require('child_process').exec;
var child;
// executes `sed`
child = exec("sed -i -e '1,1000d' file.name", function (error, stdout, stderr) {
sys.print('stdout: ' + stdout);
sys.print('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
But whenever I run same with CasperJS, it just runs forever, not executing the shell command. Maybe someone could shed some light on this.
I did actually make it work through spawn and execFile functions from PhatomJS, but the issue is that it does not work with large files over 300MB.

Can Node.js launch scripts on the server?

Can Node.js launch scripts on the server it is installed on? Scripts like bash scripts or PHP scripts, for example to resize pictures?
If so, how how is it? Can you point me to a documentation page, please?
Thanks,
Dan
Yes it is possible. The following give a demonstration:
http://www.dzone.com/snippets/execute-unix-command-nodejs
http://groups.google.com/group/nodejs/browse_thread/thread/e3d00bb0e48dd760?pli=1
You can also perform tasks such as spawning child processes, and clustering.
Executing a unix command:
var exec = require('child_process').exec;
child = exec("something", function (error, stdout, stderr) {
sys.print('stdout: ' + stdout);
sys.print('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
See Node.js Documentation for more: http://nodejs.org/api/child_process.html

Calling Make file in nested folder via Node.js

I have a complicated MakeFile file I want to call as part of my node.js app, the make file is a couple of directories deep from root. I know I need to spawn a 'make' chile process but moving node into the sub directory to call the make im not so sure about.
Сould you move the make to the nested folder? I would try something like
var util = require('util'),
exec = require('child_process').exec,
child;
child = exec('cd samples/nestedmake && make',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
(copied with minimal changes from Node Child Processes documentation).

Resources