简体   繁体   中英

Node.js / io.js: OSX How to check whether a filepath target is an application package?

For OSX, which I am fairly new to, when you have a filepath you can use fs.stat() to test whether the target is a file or a directory.

However, what I want to know is whether the directory is an application package or not. I am assuming it isn't sufficiently safe to test whether the extension is ".app". Would I need to see if there is a plist in the "folder" or ??

What would be safest way to determine whether the folder is actually an "executable" package?

Thanks.

Use the command-line utility mdls . In its output, look for the string com.apple.application-bundle .

jaanus@jk-mbp ~> mdls -name kMDItemContentTypeTree /Applications/TextEdit.app
kMDItemContentTypeTree = (
    "com.apple.application-bundle",
    "com.apple.application",
    "public.executable",
    "com.apple.localizable-name-bundle",
    "com.apple.bundle",
    "public.directory",
    "public.item",
    "com.apple.package"
)

You can execute it in Node like this:

exec = require('child_process').exec;
exec("mdls -name kMDItemContentTypeTree /Applications/TextEdit.app", function(error, stdout, stderr) {
  if (stdout.match(    "com.apple.application-bundle")) {
    console.log("is app bundle");
  } else {
    console.log("is NOT app bundle");
  }
});

I think the only proper way to test if a directory is an application package is to read the Info.plist file to check if the CFBundlePackageType is set to APPL .

Simple PoC using plist :

var fs    = require('fs');
var plist = require('plist');

var isApplication = function(dir) {
  try {
    var obj = plist.parse(fs.readFileSync(dir + '/Contents/Info.plist', 'utf8'));
    return obj.CFBundlePackageType === 'APPL';
  } catch(e) {
    return false;
  }
};

console.log( isApplication('/Applications/Mail.app') );
console.log( isApplication('/tmp') );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM