Passing a Jar arguments from Javascript in Ubuntu - javascript

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

Related

NodeJS - Run seperate functions depending on OS (Closed)

How do we run seperate functions based on the users Operating System?
I have two functions for returning relative paths to given files by searching for them recursively within subdirectories of given working directory's.
I have one for Windows, see below..
WINDOWS variant
console.log("Locating File...");
exec('set-location ' + folder + ';' + ' gci -path ' + folder + ' -recurse -filter ' +
file + ' -file | resolve-path -relative', { 'shell':'powershell.exe' }, (error, stdout, stderr) => {
var filePath = stdout.substring(stdout.indexOf(".\\") + 2).trim("\n");
if (error !== null) {
console.log("Cannot Locate the file...");
return;
}
And one for Linux & macOS, see below...
LINUX/OSX variant
console.log("Locating File...")
console.log();
exec('find -name "' + file + '"', { cwd: folder }, (error, stdout, stderr) => {
var filePath = stdout.substring(stdout.indexOf("./") + 2).trim("\n");
if (error !== null) {
console.log("Cannot Locate the file...");
return;
}
I want to execute these functions based on the users Operating System if that's possible?
I've had a look at the StackOverflow question..
How do I determine the current operating system with Node.js
which is how I found out how to detect the current user OS, as well as the StackOverflow Question..
python: use different function depending on os.
Aside from the 2nd issue referenced being for python, I am basically trying to achieve the same thing from the 2nd issue but with nodeJS, by using the solution from the 1st issue.
My latest attempt was the following below, but for some reason it doesn't return anything but a blank console.
const fs = require("fs");
const platform = require("process");
const path = require("path");
var exec = require("child_process").exec
var folder = "just/some/folder/location"
var file = "file.txt"
// Windows process
if (platform === "win32") {
console.log("Locating File...");
exec('set-location ' + folder + ';' + ' gci -path ' + folder + ' -recurse -filter ' +
file + ' -file | resolve-path -relative', { 'shell':'powershell.exe' }, (error, stdout, stderr) => {
// relative path output for Windows
var filePath = stdout.substring(stdout.indexOf(".\\") + 2).trim("\n");
if (error !== null) {
console.log("Cannot Locate the file...");
return;
} else if (process.platform === "linux" + "darwin") {
// Linux & Unix process
console.log("Locating File...")
console.log();
exec('find -name "' + file + '"', { cwd: folder }, (error, stdout, stderr) => {
// relative path output for Linux & macOS
var filePath = stdout.substring(stdout.indexOf("./") + 2).trim("\n");
if (error !== null) {
console.log("Cannot Locate file... \n\n" + error);
return;
};
console.log("found file: " + filePath);
// Read the file and show it's output to confirm everything ran correctly.
fs.readFile(path.join(folder, file), (error, data) => {
if (error) {
console.log("error reading file \n\n" + error);
return;
}
});
});
};
});
};
Problem solved, after doing a bit of research, I was using if else else if statements & process.platform wrong...
First, when I was declaring process.platform I was using...
const platform = require("process");
when according to process.platform documentation for CJS it should be...
const { platform } = require("node:process");
Second, I was using if else else if statements wrong!
In my issue stated above I was using if else else if statements with process.platform like so..
} else if (process.platform === "linux" || "darwin") {
// Linux & macOS code to execute
}
which was completely wrong!
I should have been using if else else if statements with process.platform like so...
if (process.platform === "win32") {
// Windows code to be executed!
} else if (process.platform === "linux") {
// Linux Code to be executed!
} else {
process.platform === "darwin";
// macOS Code to be executed!
}
I've managed to produce the following code which works on Windows, Linux and macOS closest to the way I need it to.
Hopefully this helps anyone new to JS like me.
const fs = require("fs");
const { platform } = require("node:process");
const path = require("path");
var exec = require("child_process").exec
var folder = "just/some/folder/location"
var file = "file.txt"
// Windows Process
if (process.platform === "win32") {
// executes Powershell's "set-location" & "gci" commands...
//...to locate a given file recursively...
//...and returns its relative path from inside the given...
//...working directory's subdirectories.
exec('set-location "' + '"' + folder + '"'
+ ';' + ' gci -path ' + '"' + folder + '"'
+ ' -recurse -filter ' + '"' + file + '"' +
' -file | resolve-path -relative', (error, stderr, stdout) => {
// sets the relative file path from ".\this\way\to\the\file.txt",
// to "this\way\to\the\file.txt".
var filePath = stdout.substring(stdout.indexOf(".\\") + 2).trim("\n");
// throw an error if the file isnt found at all!
if (error !== null) {
console.log("Cannot locate the given file... \n" + error);
return;
};
// read the file after it's been found.
fs.readFile(path.join(folder, filePath), 'utf8', (error, data) => {
if (error) {
console.log("There was a problem reading the given file... \n" + error);
return;
};
// Then print the data from fs.readFile...
//...to confirm everthing ran correctly.
console.log(data);
});
});
} else if (process.platform === "linux") {
// executes findUtil's "find" command...
//...to locate a given file recursively...
//...and return its relative path from inside the given...
//...working directory's subdirectories.
exec('find -name "' + file + '"', { cwd: folder }, (error, stderr, stdout) => {
// sets the relative file path from "./this/way/to/the/file.txt",
// to "this/way/to/the/file.txt".
var filePath = stdout.substring(stdout.indexOf("./") + 2).trim("\n");
// throw an error if the file isnt found at all!
if (error !== null) {
console.log("Cannot locate the given file... \n" + error);
return;
};
// read the file after it's been found.
fs.readFile(path.join(folder, filePath), 'utf8', (error, data) => {
if (error) {
console.log("There was a problem reading the given file... \n" + error);
return;
};
// Then print the data from fs.readFile...
//...to confirm everthing ran correctly.
console.log(data);
});
});
} else {
// Uses APPLES built BSD findUtils 'find' command to locate the file inside the folder and subdirectories
exec('find ' + '"' + apkFolder + '"' + ' -name ' + '"' + file + '"', (error, stderr, stdout) => {
// sets the relative file path from "./this/way/to/the/file.txt",
// to "this/way/to/the/file.txt".
var filePath = stdout.substring(stdout.indexOf("./") + 2).trim("\n");
// throw an error if the file isnt found at all!
if (error !== null) {
console.log("Cannot locate the given file... \n" + error);
return;
};
// read the file after it's been found.
fs.readFile(path.join(folder, filePath), 'utf8', (error, data) => {
if (error) {
console.log("There was a problem reading the given file... \n" + error);
return;
};
// Then print the data from fs.readFile...
//...to confirm everthing ran correctly.
console.log(data);
});
});
}

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)

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

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?

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

Possible to open and write to local files using javascript?

At work I have to repeat this same process multiple times:
Open a certain Dreamweaver file.
Look for all <p> tags and replace then with <h1> tags.
Look for all </p> and replace with </h1>.
Look for the string 'Welcome' and replace with 'goodbye'.
Look for '0:01:00' and replace with '01:00'.
Copy everything in that file.
Create a new Dreamweaver file and paste everything in the new file.
Save the new file in a given directory and call it a certain name, which can be provided as a variable.
I don't need to run the JavaScript from a browser. It can be a JavaScript file which I just double click on the desktop.
Is it possible for me to do this with JavaScript / jQuery?
There are many other programming languages that you could accomplish this task with but if you really want to use Javascript then you could do the following:
var fs = require('fs');
if(process.argv.length < 4) {
console.log('Usage: node replace.js fromFilePath toFilePath');
return;
}
from = process.argv[2];
to = process.argv[3];
fs.readFile(from, { encoding: 'utf-8' }, function (err, data) {
if (err) throw err;
console.log('successfully opened file ' + from);
var rules = {
'<p>': '<h1>',
'</p>': '</h1>',
'Welcome': 'goodbye',
'0:01:00': '01:00'
};
for(var index in rules) {
console.log('Replacing ' + index + ' with ' + rules[index] + '...');
data = data.replace(new RegExp(index, 'gi'), rules[index]);
console.log('Done');
}
console.log("Result");
console.log(data);
console.log("Writing data to " + to);
fs.writeFile(to, data, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
INSTRUCTIONS
Download node.js from here
Install it
Create a file in C:\replace.js (Win) or ~/replace.js (Mac OS)
Put the code from above in replace.js
Open cmd (Ctrl+R on Win) or Terminal (on Mac OS)
Type node C:\replace.js <fileToReadFrom> <fileToSaveTo> on Win or node ~/replace.js <fileToReadFrom> <fileToSaveTo> on Mac OS
Done

Categories

Resources