1

I have a piece of JavaScript that is designed to be run inside NodeJS, otherwise it breaks (for instance, it makes use of require()). I'd like to make a runtime check that it's inside NodeJS and produce a clear error message otherwise.

I've seen this answer explaining how to check if the code is being run inside browser. However it doesn't check if there's NodeJS.

How do I check my JavaScript is run inside NodeJS?

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • Are you designing your code to run in more than one environment? If not, then surely there's no need to check if the environment is the correct one... it's the user's responsibility to check which environment it is for. – Nathan MacInnes Jan 18 '13 at 12:02
  • @Nathan MacInnes: Well, in real life users run the code wherever they want and then email us and ask why they have tons of weird errors. – sharptooth Jan 18 '13 at 12:06
  • This happens to be a duplicate of http://stackoverflow.com/q/4224606/57428 – sharptooth Jan 18 '13 at 12:10

2 Answers2

3

A bullet-proof solution would check for the global window object. In a browser, it exists, and it cannot be deleted. In node.js, it doesn't exist, or if it does (because someone defined it), it can be deleted. (In node.js, the global object is called GLOBAL and it can be deleted)

A function that does that would look like this:

function is_it_nodejs() {
  if (typeof window === 'undefined') return true;

  var backup = window,
      window_can_be_deleted = delete window;
  window = backup; // Restoring from backup

  return window_can_be_deleted;
}
molnarg
  • 2,775
  • 1
  • 19
  • 20
2

One thing you could to is to check whether the process object is defined and whether the first element of the process.argv array is node.

Something like:

if(typeof process !== 'undefined' && process.argv[0] === "node") {
    // this is node
}

More info in the docs.

Andrey
  • 671
  • 10
  • 23