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)
Related
I have a node js script that spawns a non-terminating powershell script and listens for data:
node js script:
"use strict";
const cp = require("child_process");
const psData = cp.spawn
("powershell -executionpolicy bypass ./powershell-script.ps1", [], {
shell: "powershell.exe",
serialization: "json",
windowsHide: true,
});
psData.stdout.on("data", function (_data) {
try {
const psObj = JSON.parse(_data);
console.log(psObj);
} catch (e) {
console.error("Failed to Parse JSON!", e);
console.log(_data.toString());
}
});
powershell script:
function getData {
# some irrelevant code +
if ($readData -ne "")
{
$data = [ordered]#{
type = "text";
value = $readData;
}
$data = $data | ConvertTo-Json
Write-Output $data
}
}
while ($true) {
gedData
Start-Sleep -Milliseconds 250
}
The combination works fine up until $data in the ps script goes over a few kb, when that happens it looks like Write-Output splits the data in chunks and after writing each chunk it triggers the 'data' event and therefore
the psData.stdout.on("data",){} in the node script is triggered, so instead of getting a valid JSON file node gets parts of it and throws an error.
I reckon the Write-Output method splits the data, is there a way to increase its buffer size?
Any other ideas?
Thanks!
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
Trying to create a new csv file in a directory.
I want to store the data of a variable inside that csv file:
handleRequest(req, res) {
var svcReq = req.body.svcReq;
var csvRecData = JSON.stringify(req.body);
console.log("DATA WE ARE GETIING IS: " + csvRecData);
if (svcReq == 'invDetails') {
var checking = fs.writeFile('../i1/csvData/myCsvFile.csv', csvRecData, function (err) {
if (err) throw err;
console.log("Saved! got the file");
console.log("Checking csvData:" + checking);
});
}
}
I don't see any errors in the console or terminal but the file is not generated. What is my issue?
The path in writeFile should be pointed correctly..you cannot simply use "../il/csv" from your current file.First check your current directory using path.
1)Install path npm module
2)
var path = require('path');
var fs = require('fs');
console.log(path.join(__dirname))
fs.writeFile((path.join(__dirname)+"/test123.csv"), "Sally Whittaker,2018,McCarren House,312,3.75!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
how should I proceed to create an output like this in bash with nodejs
$ echo “Hello World” > foo.txt //creating the text file
$ ./test < foo.txt // launching the test.js script with the text file as input
Hello World //result
I've tried
test.js
#!/usr/bin/env node
var fs = require('fs');
fs.readFile('how to get foo.txt path enterd as input ?','utf8', function(err, data) {
if(err) throw err;
var array = data.toString().split("\n");
for(i in array) {
console.log(array[i]);
}
});
The script below will read the contents of foo.txt into the chunks variable. When the stream is finished the contents will output to console.
//node thisFile.js foo.txt
//console.log(process.argv) will tell you what the CLI inputs are
fileName = process.argv[2];
input = fs.createReadStream(fileName);
var chunks = '';
input.on('data' , function(data){
chunks += data;
});
input.on('end', function(){
console.log('blow ' + chunks);
});
Is this what you're asking?
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.');
});