Detect If You’re Running a Node.js Script with Bun

The Bun JavaScript runtime is still in an early stage of development at the time of writing this tutorial. It’s not 100% compatible with Node.js and there are a handful of APIs missing for full interoperability.

If you still want to support Bun, you may need to adjust your project code with conditional checks whether you’re in a Bun environment or not. This tutorial shows you how to do that and detect whether your code runs with Bun.

Bun Series Overview

Check If Your Code Runs in Bun

Bun strives for feature parity with Node.js. That means it supports most of the Node.js globals already. To check if you’re running your code with Bun, check for Bun’s version. You can detect the Bun version using the process.versions object.

The process.versions.bun variable is available if you’re in a Bun environment:

if (process.versions.bun) {  
  console.log('DUDE! You’re using Bun!')
} else {
  console.log('You’re not using Bun')
}

Run the code with Bun and Node.js and check the related outputs:

$ bun server.js
'DUDE! You’re using Bun!'

$ node server.js
'You’re not using Bun'  

It works, sweet!

What about the Bun Global?

You can also detect whether your code runs in a Bun environment by checking for the existence of the global Bun variable.

This only works if you’ve installed the `bun-types` package. Otherwise, you’re running into type errors. The suggested checks above always work.  

Here’s the sample code checking for the Bun global:

if (typeof Bun !== "undefined") {  
  // you’re running your code with Bun
}

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.