How to check if a file is executable in node.js?

How to check if a file is executable in node.js?

Maybe something like

fs.isExecutable(function (isExecutable) {

})
+6
source share
5 answers

You must use a call to do this fs.stat.

The call fs.statreturns the fs.Stats object .

This object has an attribute mode. The mode will tell you if the file is executable.

In my case, I created the file and made chmod 755 test_fileand then executed it through the following code:

var fs = require('fs');
test = fs.statSync('test_file');
console.log(test);

What I got for test.modewas 33261.

This link is useful for converting modeback to equivalent unix file permissions.

+7
source

, fs - fs.access, fs.accessSync. , . :

const fs = require('fs');

fs.access('./foobar.sh', fs.constants.X_OK, (err) => {
    console.log(err ? 'cannot execute' : 'can execute');
});
+8

https://www.npmjs.com/package/executable, .sync()

executable('bash').then(exec => {
    console.log(exec);
    //=> true 
});
+3

Node fs.stat fs.Stats, fs.Stats.mode. : Nodejs

+2

. , which where, . Windows Posix (Mac, Linux, Unix, Windows, Posix, Posix).

const fs = require('fs');
const path = require('path');
const child = require("child_process");

function getExecPath(exec) {
  let result;
  try {
    result = child.execSync("which " + exec).toString().trim();
  } catch(ex) {
    try {
      result = child.execSync("where " + exec).toString().trim();
    } catch(ex2) {
      return;
    }
  }
  if (result.toLowerCase().indexOf("command not found") !== -1 ||
      result.toLowerCase().indexOf("could not find files") !== -1) {
    return;
  }
  return result;
}    


function isExec(exec) {
  if (process.platform === "win32") {
    switch(Path.GetExtension(exec).toLowerCase()) {
      case "exe": case "bat": case "cmd": case "vbs": case "ps1": {
        return true;
      }
    }
  }
  try {
    // Check if linux has execution rights
    fs.accessSync(exec, fs.constants.X_OK);
    return true;
  } catch(ex) {
  }
  // Exists on the system path
  return typeof(getExecPath(exec)) !== 'undefined';
}
0

All Articles