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