I have a script I am requiring from a Node.js script, which I want to keep JavaScript engine independent.
For example, I want to do exports.x = y;
only if it’s running under Node.js. How can I perform this test?
When posting this question, I didn’t know the Node.js modules feature is based on CommonJS.
For the specific example I gave, a more accurate question would’ve been:
How can a script tell whether it has been required as a CommonJS module?
I currently stumbled over a wrong detection of Node which is not aware of the Node-environment in Electron due to a misleading feature-detection. The following solutions identify the process-environment explicitly.
Identify Node.js only
This will discover if you're running in a Node-process, since
process.release
contains the "metadata related to the current [Node-]release".After the spawn of io.js the value of
process.release.name
may also becomeio.js
(see the process-doc). To proper detect a Node-ready environment i guess you should check as follows:Identify Node (>= 3.0.0) or io.js
This statement was tested with Node 5.5.0, Electron 0.36.9 (with Node 5.1.1) and Chrome 48.0.2564.116.
Identify Node (>= 0.10.0) or io.js
@daluege's comment inspired me to think about a more general proof. This should working from Node.js >= 0.10. I didn't find a unique identifier for prior versions.
P.s.: I am posting that answer here since the question lead me here, although the OP was searching for an answer to a different question.
Here's a pretty cool way to do it as well:
This works because in browsers the global 'this' variable has a self reference called 'window'. This self reference is not existent in Node.
To break the above suggested browser check you would have to do something like the following
before executing the check.
Edit: Regarding your updated question: "How can a script tell whether it has been required as a commonjs module?" I don't think it can. You can check whether
exports
is an object (if (typeof exports === "object")
), since the spec requires that it be provided to modules, but all that tells you is that ...exports
is an object. :-)Original answer:
I'm sure there's some NodeJS-specific symbol (
no, you have to useEventEmitter
, perhapsrequire
to get the events module; see below) that you could check for, but as David said, ideally you're better off detecting the feature (rather than environment) if it makes any sense to do so.Update: Perhaps something like:
But that just tells you that you're in an environment with
require
and something very, very much like NodeJS'sBuffer
. :-)The following works in the browser unless intentionally,explicitly sabotaged:
Bam.
I'm using
process
to check for node.js like soor
Documented here