node.js脚本查找程序路径
发布于 9个月前 作者 novembereleven 564 次浏览

今天想更新node,但找不到node原本装在哪里= =!于是就有了这个脚本。可以查找应用程序安装目录。

通过运行$PATH/APPNAME -v来判断程序的exit code是否不为-1来判断程序是否存在。

#!/usr/bin/env node
var path = require('path'),
    spawn = require('child_process').spawn;

// usage: whereis.js APPNAME
if (process.argv.length < 3 || process.argv.length >3) {
    console.log('usage: whereis.js APPNAME');
    process.exit(1);
}

var paths = process.env.PATH.split(':');
var app = process.argv[2];
var finished = 0;

for(var i = 0; i < paths.length; i++) {
    var cmd = path.join(paths[i], app);
    var appRun = spawn(cmd, ['-v']);
    (function(path, appRun) {

        appRun.on('close', function(code) {
            if(code != -1) {
                console.log('app path: %s', path);
                process.exit(0);
            }
            finishOne();
        });
        appRun.on('error', function(error) {
            
        });
    })(paths[i], appRun);
}

function finishOne() {
    finished++;
    if (finished == paths.length) {
        console.log('No such app');
    }
}


使用fs.exists判断

#!/usr/bin/env node
var path = require('path'),
    fs = require('fs');

// usage: whereis.js APPNAME
if (process.argv.length < 3 || process.argv.length >3) {
    console.log('usage: whereis.js APPNAME');
    process.exit(1);
}

var paths = process.env.PATH.split(':');
var app = process.argv[2];
var finished = 0;

for(var i = 0; i < paths.length; i++) {
    var fullPath = path.join(paths[i], app);
    (function(path) {
        fs.exists(fullPath, function(exists) {
            if (exists) {
                console.log('app path: %s', path);
                process.exit(0);
            }
            finishOne();
        });
    })(fullPath);
}

function finishOne() {
    finished++;
    if (finished == paths.length) {
        console.log('No such app');
    }
}


截图

3 回复

原来还可以 -v 判断 挺好

回到顶部