How to check my code is run inside NodeJs?

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?

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

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.