Search code examples
javascriptnode.jsoperating-systemchild-process

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

             });
        };
   });
};


Solution

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