Search code examples
node.jsmacosnode-webkitfinder

Finder aliases not recognized as symlinks on a Mac with node.js


I am running a nodewebkit application, and I want to search a folder for aliases.

The following code is working, but not recognizing folder aliases or file aliases as symbolic links.

Where am I wrong?

    var path = '/Users/test/Desktop/testfolder';
    var fs = require('fs');
    fs.readdir(path, function(err, files) {
        if (err) return;
        files.forEach(function(f) {
            var newPath = path + '/' + f;
            console.log("looking for "+ newPath +" symlink: "+fs.lstatSync(path).isSymbolicLink());
            fs.lstat(newPath, function(err, stats){
                if(err){
                    console.log(err);
                }
                if(stats.isFile()){
                    console.log('is file mofo',f);
                }
                if(stats.isDirectory()){
                    console.log('is Directory mofo',f);
                }
                if(stats.isSymbolicLink()){
                    console.log('is symbolic link');
                }
            });
        });
    });

Solution

  • Finder aliases on OS X are technologically distinct from symlinks.

    From the filesystem's perspective, they are regular files, and only Finder itself and the OS X-specific APIs know to handle them - Node.js has no built-in API for that.

    IF calling out to the shell - which will be slow - is an option, you can try the following:

    function isFinderAlias(path) {
      var contentType = require('child_process')
            .execFileSync('mdls', 
              [ '-raw', '-name', 'kMDItemContentType', path ], { encoding: 'utf8' })
      return contentType === 'com.apple.alias-file'
    }
    

    For a swift-based way to resolve a Finder alias to its target path, see this answer.