检查脚本是 Node 还是 Phantom

Check whether script is Node or Phantom

我有一个公共模块,为我的项目提供公共目录,NodeJS 和 PhantomJS 脚本都使用它。任何人都知道如何 return 哪个脚本是 运行 的简单明确功能,如果 node.jsphantom.js?

目前我用的是这个方法,不知道是不是最好的方法

//parent directory of project directory tree
//tries to get according to Engine, Node or PhantomJS
var ROOT_DIR;
if (typeof __dirname !== 'undefined'){//nodeJS has __dirname
    ROOT_DIR = path.resolve(__dirname, '.')  + "/";
    console.log("ROOT_DIR got on Node: " + ROOT_DIR);
}
else {//PhantomJS?         
    try{
        var fs = require('fs');
        ROOT_DIR = fs.absolute("./"); //it already leaves a trailing slash
        console.log("ROOT_DIR got PhantomJS: " + ROOT_DIR);
    }
    catch(err){
        throw "Engine not recognized, nor NodeJS nor PhantomJS";    
    }
}

编辑:这个问题与仅仅检测节点略有不同,因为这里我们也尝试检测 PhantomJS,即区别不在节点和浏览器之间,而是在节点之间和幻影。当然,节点的检测是类似的,但是很多检测节点是否为 运行 的方法,在 PhantomJS 中可能会抛出异常。

这行得通吗?

const isNode = () => {
  return process && process.argv[0] === 'node';
};

我用这个检测是否是nodeJS

if ((typeof process !== 'undefined') &&
    (process.release.name.search(/node|io.js/) !== -1)){//node
}
else{//not node, im my case PhantomJS
}

它使用节点 process 对象,并且由于其他模块可能具有该对象名称,因此在其中确保属性 process.release.name 具有 'node' 或 'io.js' .