0

I have a common module, providing the common directories for my project, which is used by both NodeJS and PhantomJS scripts. Anyone is aware of a simple clear function on how to return which script is running, if node.js or phantom.js?

For now, I use this method, but I don't know if it is the best approach

//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";    
    }
}

Edit: this issue is slightly different from merely detecting node, since here we try also to detect PhantomJS, i.e., the difference is not between node and a browser but between node and phantomjs. Of course that the detection of node is similar, but many approaches to detect whether node is running or not, might in PhantomJS throw an exception.

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109

2 Answers2

0

Could this work?

const isNode = () => {
  return process && process.argv[0] === 'node';
};
Moritz Schmitz v. Hülst
  • 3,229
  • 4
  • 36
  • 63
0

I used this to detect whether is nodeJS

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

It uses the node process object and since other modules might have that object name, within it it assures that attribute process.release.name has 'node' or 'io.js' within it.

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109