【问题标题】:Check whether script is Node or Phantom检查脚本是Node还是Phantom
【发布时间】:2018-02-08 21:35:57
【问题描述】:

我有一个公共模块,为我的项目提供公共目录,NodeJS 和 PhantomJS 脚本都使用它。如果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";    
    }
}

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

【问题讨论】:

  • 不确定 PhantomJs,但在 node 中,您可以访问在运行时传递给 node 的参数。第一个参数是节点(或不是)。
  • @MoritzSchmitzv.Hülst 你是说我只需要制作if (process.argv[0] === 'node') 吗?有趣,但如果在 PhantomJS 中没有 process 则会抛出异常。
  • 编辑了我的解决方案。只需检查进程即可。

标签: node.js phantomjs


【解决方案1】:

这行得通吗?

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

【讨论】:

  • PhantomJS 没有process,表示会抛出异常。
  • 还是不行,要检查变量是否存在你必须做typeof process !== 'undefined'
【解决方案2】:

我用这个来检测是否是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”。

【讨论】:

    猜你喜欢
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2023-02-07
    • 2022-12-06
    • 1970-01-01
    • 2013-12-10
    • 2011-02-12
    相关资源
    最近更新 更多