Heya,

> Is there a way to detect whether we run on node?

There doesn't seem to be any _one_ reliable way to determine the JS engine, but 
there are heuristics:

* the `window` global usually only exists in web browsers[0]
* the `process` global exists in Node.js[1] but not web browsers (Deno is 
supposed to be Node.js-compatible[2], so it exists there too)
* in Node.js, `process.release.name` always has the value 'node'[3] (based on 
the docs, that's case for Deno too[4], weirdly enough? I didn't actually try 
that in a REPL)
* in Node.js >=0.10.0, `process.versions.node` exists[5][6] (and in Deno too[7])
* in Bun, `process.versions.bun` exists[8]

The following should work well enough if you don't define these variables 
yourself[9][10]:

if (typeof window !== 'undefined') {
  // probably web browser
} else if (typeof process !== 'undefined' && process.versions.node) { // or 
`process.release.name === 'node'`
  // probably Node.js/Deno
} else if (typeof process !== 'undefined' && process.versions.bun) {
  // probably Bun
}

[0] https://developer.mozilla.org/en-US/docs/Web/API/Window
[1] https://nodejs.org/docs/latest-v22.x/api/globals.html#process
[2] https://docs.deno.com/runtime/fundamentals/node/
[3] https://nodejs.org/docs/latest-v22.x/api/process.html#processrelease
[4] https://docs.deno.com/api/node/process/~/Process.release
[5] 
https://nodejs.org/docs/latest-v0.10.x/api/process.html#process_process_versions
[6] https://nodejs.org/docs/latest-v22.x/api/process.html#processversions
[7] https://docs.deno.com/api/node/process/~/Process.versions
[8] 
https://github.com/oven-sh/bun/blob/4760d78b325b62ee62d6e47b7e8b29e58099bf4a/docs/guides/util/detect-bun.mdx
[9] https://stackoverflow.com/a/4224668
[10] https://stackoverflow.com/a/35813135

Hope that's not TMI :p

siiky



Reply via email to