In the "Main.js", i use spawn to create a child_process.I want get data from "work.js",but it show error
TypeError: out.clearLine is not a function
If use node work.js in the terminal,it works fine。
It seems like process.stdout does't have function "clearLine" in childProcess.
main.js
var spawn = require('child_process').spawn;
var child = spawn('node',['work.js']);
child.stdout.on('data', function (data) {
console.log('data:',data.toString());
})
child.stderr.on('data', function (data) {
console.log("stderr:", data.toString());
});
work.js
var out = process.stdout;
var idx = 0;
var id = setInterval(()=>{
idx++;
out.clearLine();
out.cursorTo(0);
out.write('workTime:' + idx);
if(idx>3){
clearInterval(id);
console.log();
console.log('end')
}
},100)
It's just a demo, i cant't change the work.js. How can i fix the problem in main.js,thanks
See: node.js stdout clearline() and cursorTo() functions
var readline = require('readline');
function writeWaitingPercent(p) {
//readline.clearLine(process.stdout);
readline.cursorTo(process.stdout, 0);
process.stdout.write(`waiting ... ${p}%`);
}
Related
I am working on a log tail project using node.js but the function process.createChildProcess is not working.Is there any alternative to that?
var sys = require('sys');
var filename = "test.txt";
var process=require('process')
if (!filename)
return sys.puts("Usage: node watcher.js filename");
// Look at http://nodejs.org/api.html#_child_processes for detail.
var tail = process.createChildProcess("tail", ["-f", filename]);
sys.puts("start tailing");
tail.addListener("output", function (data) {
sys.puts(data);
});
// From nodejs.org/jsconf.pdf slide 56
var http = require("http");
http.createServer(function(req,res){
res.sendHeader(200,{"Content-Type": "text/plain"});
tail.addListener("output", function (data) {
res.sendBody(data);
});
}).listen(8000);
Here I am getting error:
var tail = process.createChildProcess("tail", ["-f", filename]);
^
TypeError: process.createChildProcess is not a function
Any help will be appreciated
Article referred: https://thoughtbot.com/blog/real-time-online-activity-monitor-example-with-node-js-and-websocket
You can use spawn for creating a child process in Node.JS.
Here's an example based on your code:
const { spawn } = require('child_process');
/* Some Code Here! */
var tail = spawn("tail", ["-f", filename]);
I would like to run an exe in Windows from my Node Webkit app.
I am trying the below code but it is not working.
document.getElementById('play').onclick = function()
{
var spawn = require('child_process').spawn;
var child = spawn(__dirname + '/core.exe', ['/arg1']);
var snd = new Audio("min.wav");
snd.play();
win.minimize();
child.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
child.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
child.on('close', function (code) {
console.log('child process exited with code ' + code);
var snd = new Audio("restore.wav");
snd.play();
win.restore();
});
}
Am I getting the path wrong? I need it to be current directory and run the exe with that name and the example arg.
The output SHOULD be a messagebox, but nothing loads.
Managed to figure it out, it wasn't defined because I was using it in browser context. I didn't get the nw.js SDK version for some reason, found that __DIRNAME was undefined. Came up with this solution instead.
var path = require('path');
var nwDir = path.dirname(process.execPath);
var spawn = require('child_process').spawn;
var child = spawn(nwDir + '/app/core.exe', ['/arg1']);
Now working as intended.
I need to call to CMD command from my node JS application ,
is it possible ?
I try with the following (POC) and I got error
var express = require('express');
var app = express();
app.get('/', function (req, res) {
function cmd_exec(cmd, args, cb_stdout, cb_end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
me.exit = 0; // Send a cb to set 1 when cmd exits
child.stdout.on('data', function (data) {
cb_stdout(me, data)
});
child.stdout.on('end', function () {
cb_end(me)
});
}
foo = new cmd_exec('npm', 'install glob --save',
function (me, data) {
me.stdout += data.toString();
},
function (me) {
me.exit = 1;
}
);
setTimeout(
// wait 0.25 seconds and print the output
log_console,
250);
function log_console() {
console.log(foo.stdout);
}
res.send("Hello world");
});
I saw this code in the following link
node.js shell command execution
The error is :
TypeError: Incorrect value of args option
in line child = spawn(cmd, args),
what am I doing wrong here ?Currnlty I just use the npm install command(just for testing) but any other command that I can execute and run will be sufficient
When executing a terminal command, there are two parts: The command, and the arguments. In your case, the command is npm, and the arguments is everything that comes after that.
cmd_exec('npm', ['install', 'glob', '--save'],
This gulp task hangs on exec('node config/app') line. first exec works fine but the second just hangs.
gulp.task('test', function(cb) {
var exec = require('child_process').exec;
exec('echo 3', function(err, stdout) {
console.log(stdout);
});
exec('node config/app', function(err, stdout, stderr) {
console.log(stdout);
var testemOptions = {
file: 'testem.json'
};
var t = new testem();
return t.startCI(testemOptions, function() {
cb();
});
});
});
I can see the output 3 but no output is shown for the second console.log.
I am trying to run my server before running the tests with testem.
I've tried this similar solution but it doesn't work: Exec not returning anything when trying to run git shortlog with nodejs.
Also I've recently asked a hanging testem gulp task question: Testem gulp task hangs after finished.
Edit:
My current solution is:
gulp.task('test', /*['build'],*/ function(cb) {
var spawn = require('child_process').spawn;
var proc = spawn('node', ['config/app']);
proc.stdout.on('readable', function() {
var output = proc.stdout.read();
if (output && output.toString().match('express listening')) {
var testemOptions = {
file: 'testem.json'
};
var t = new testem();
t.startCI(testemOptions, function() {
proc.kill();
cb();
});
}
});
});
If you want to use testem to test the "node config/app" server, you cannot use exec.
Exec is supposed to callback when the command is finished so in your case it will never callback.
try with
gulp.task('test', function(cb) {
var spawn = require('child_process').spawn;
var proc = spawn('node', ['config/app']);
var testStarted = false;
proc.stdout.on('readable', function() {
if (testStarted) return;
testStarted = true;
var testemOptions = {
file: 'testem.json'
};
var t = new testem();
t.startCI(testemOptions, function() {
proc.kill()
cb();
});
}
});
Note that I did not test this code and that it probably does not handle all the corner cases you might encounter (if the server stops unexpectedly for example)
you may also want to check the plugin https://github.com/sargentsurg/gulp-testem
There is ŧestem plugin on github.
I am using the readline module to create a command line interface (CLI) for an application in Node.js.
The problem is that I can not scroll up to view the past commands as I usually can in Terminal. My CLI is just a fixed window and if I print too much out to the screen, I lose information at the top and there is no way to scroll up to see it.
(I am running my program on Mac OSX Mavericks)
Thanks in advance.
Code Snippet:
var readline = require('readline');
var Cli = function () {
this.txtI = process.stdin;
this.txtO = process.stdout;
process.stdout.write('CLI initialized.');
this.rl = readline.createInterface({input: this.txtI, output: this.txtO });
this.rl.setPrompt('>>>');
this.rl.prompt();
this.rl.on('line', function(line) {
var input = line.toString().trim();
if (input) {
this.txtO.write('cmd: ' + input);
}
this.rl.prompt();
}.bind(this)).on('close', function() {
this.txtO.write('Have a great day!');
process.exit(0);
}.bind(this));
};
new Cli();
Save this file as snippet.js and run
node snippet.js
in terminal.
It probably is working, just readline is overwriting your line. Try outputting multiple lines:
process.stdout.write("1\n2\n3\n4\n5");
Readline is quite an awesome module. History is already there. As is the possibility to add completion. Try the snippet below.
var readline = require('readline');
function createCLI(opt) {
var rl = readline.createInterface({
input : opt.input,
output : opt.output,
terminal : opt.terminal || true,
completer : opt.completer ||
function asyncCompleter(linePartial, callback){
var completion = linePartial.split(/[ ]+/);
callback(null, [completion, linePartial]);
}
});
rl.on('line', function(line) {
if( !line.trim() ){ this.prompt(); }
else { this.write(line); }
}).on('close', function() {
this.output.write('\n Have a great day!');
process.exit(0);
}).setPrompt(' > ');
rl.output.write(' CLI initialized\n');
return rl;
}
var cli = createCLI({
input : process.stdin,
output : process.stdout
});
cli.prompt();