Execute a terminal command using node.js and capture its output - javascript

I am trying to execute following terminal command to output some doc file:
"02:00:00:04" -s doc > 111.doc
Also have to run this through node.js:
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var fs = require('fs');
var workDir = process.env.TSHARK
var args = ['02:00:00:04' ,'-S','doc']
logStream = fs.createWriteStream(workDir + '//111.doc');
var spawn = require('child_process').spawn,
child = spawn('tshark', args, {cwd: workDir});
child.stdout.pipe(logStream);
child.stderr.pipe(logStream);
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('closing code: ' + code);
});
Directly running the terminal command outputs a valid file
But running the above node script not getting the full file (last lines are missing).
What is wrong with my code?

Related

How to I make newman library take the csv file sequentially?

This is my code
var fs = require('fs'),
path = require('path');
cheerio = require('cheerio'),
newman = require('newman'),
os = require("os");
const directoryPath = path.join(__dirname, './payload');
fs.readdir(directoryPath, function(err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
files.forEach(function(file) {
console.log("Files Read")
runNewman(file);
});
});
function runNewman(data) {
let logs=[];
var csvFile = "payload/" + data;
//var logFile = "payload/" + data + ".txt";
newman.run({
collection: require('./kmap_testing.postman_collection.json'),
environment: require('./kmap.postman_environment.json'),
globals: require('./My Workspace.postman_globals.json'),
reporters: 'cli',
iterationData:csvFile
}).on('start',function(err,args){
console.log('start');
}).on('console',function(err, args){
if(err){return;}
logs.push(args.messages);
}).on('done',function(err, summary){
if(err || summary.error){
console.error('collection run encounter an error');
}
else{
console.log('collection run completed');
}
fs.appendFileSync("results.csv",logs.join("\r\n"));
})
}
I have huge csv file with almost 100K+ data, I have split the data into 5K per csv file and saved them under Payload folder. However, newman.run - takes the files randomly or parallely and runs. The results.csv file ends up running two times and has more than 200K + results. Someone, please help me with this? I am a beginner with newman library.

Process Spawns With "stdio: 'inherit' " But Not "stdio: 'pipe' "

I'm trying to pipe the console output of a child Python process to a parent Node.js process. I'm able to spawn a Python process successfully, and the output from the Node parent process successfully is outputted live to the webpage.
However, I can't send the output from the child process (Python script). The Python script successfully launches if I use the parameter "stdio: 'inherit'", but I require "stdio: 'pipe'", to output the terminal, and for some reason it doesn't work.
Server Code
app.post('/clientwebpageoutput', function(req,res)
{
var io = require('socket.io')(http);
var child = require('child_process');
var events = require('events');
var eventEmitter = new events.EventEmitter();
eventEmitter.on('logging', function(message) {
io.emit('log_message', message);
});
io.on('connection', function(socket){
console.log('Before process begins');
var python_process = child.spawn( 'python3', ['snowboymultiplemodels.py'], {stdio: 'pipe'});
var chunk = '';
python_process.stdout.on('data', function(data){
chunk += data
socket.emit('newdata', chunk);
} );
python_process.stderr.on('data', function (data) {
console.log('Failed to start child process.');
})
});
// Override console.log
var originConsoleLog = console.log;
console.log = function(data) {
eventEmitter.emit('logging', data);
originConsoleLog(data);
};
res.render('clientwebpageoutput'); //,output);
});
Client (successfully outputs stderr):
<script src="/socket.io/socket.io.js"></script>
<script>
$(function () {
var socket = io();
socket.on('log_message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
Why does the process not spawn? The terminal always shows the error message created above in stderr ("Failed to start child process").

Passing a Jar arguments from Javascript in Ubuntu

I've got a Javascript snippet I am using successfully to pass arguments to a jar file for calculations on my windows machine but when I uploaded it to my server its telling me it cannot access the jar file. I can run the jar file from terminal on my Ubuntu server so I am not entire sure why it's not working from the JavaScript file.
const cmdArgs = [...vendFat, priceFat, amountFat];
/* variable 'command line code' */
const cmdCode = `java -jar ./Java2/createOrder.jar ${cmdArgs}`;
var exec = require('child_process').exec, child;
child = exec(cmdCode,
function (error, stdout, stderr){
console.log('Response: ' + JSON.stringify(stdout));
res.send(stdout);
//console.log('stderr: ' + stderr);
if(error !== null){
console.log('exec error: ' + error);
}
});
And here is the terminal response:
exec error: Error: Command failed: java -jar ./Java2/createOrder.jar s,e,l,l,0,100
Error: Unable to access jarfile ./Java2/createOrder.jar

Pass variable from JavaScript to Windows batch file

Is it possible to create a variable in JavaScript and pass it to a batch file?
Just as a simple test echo a variable and move a file up a directory.
JavaScript.js
var s = "Gwen Stefani";
var myFile = "C:\\temp\\myfile.txt"
myBat.execute();
myBat.bat
echo s
move myFile ..
An alternative is to create a string which is saved out as a batch file and then executed, but I was wondering if if it could be done directly.
You can use command line arguments (as you are using exec I suppose this is node.js):
var s = "Gwen Stefani";
var myFile = "C:\\temp\\myfile.txt"
const exec = require('child_process').exec;
const child = exec('cmd /c myBat.bat '+ myFile+' '+s,
(error, stdout, stderr) => {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
or for extendscript:
var s = "Gwen Stefani";
var myFile = "C:\\temp\\myfile.txt";
system.callSystem('cmd /c myBat.bat '+ myFile+' '+s');
and the bat file:
echo %2
move "%~1" ..
(mv is unix command but not from windows shell)

Create a file in javascript

I want to create a text file in javascript. I have tried this, but it doesn't work:
var file_name=dir+'/aaa.txt';
var fso = CreateObject('Scripting.FileSystemObject');
var s = fsoo.CreateTextFile(file_name, True);
s.Close();
I need to create an empty file to a path.
UPDATE1:
I have also tried this, but doesn't work. Also I can not import System.IO:
var file_name='aaa.txt';
StreamWriter sw = new StreamWriter(file_name);
sw.WriteLine("This is the line");
sw.Close();
UPDATE2:
I also have tryed to execute a unix comand that does 'touch file_name'. However this doesn't work either:
var sys = require('sys')
var exec = require('child_process').exec;
var child;
child = exec(\"touch\" + file_name, function (error, stdout, stderr) {
sys.print('stdout: ' + stdout);
sys.print('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
Does anyone know how I should create a file in javascript?
This project on github looks promising:
https://github.com/eligrey/FileSaver.js
FileSaver.js implements the W3C saveAs() FileSaver interface in
browsers that do not natively support it.
Also have a look at the demo here:
http://eligrey.com/demos/FileSaver.js/
Node.js has a library called FS
FS Tutorial
You can easily create files using a built in function as so,
// include node fs module
var fs = require('fs');
// writeFile function with filename, content and callback function
fs.writeFile('newfile.txt', 'Learn Node FS module', function (err) {
if (err) throw err;
console.log('File is created successfully.');
});

Categories

Resources