At its core, CO2.js takes an input of bytes and returns in carbon estimate in grams. In doing so, it provides a way for developers to estimate the carbon cost of data transfer.
In this tutorial, you will install CO2.js in a Node environment. Then, you will calculate the CO2 emissions of transferring 1 gigabyte (GB) of data.
You can follow along with this tutorial in your local development environment, or by using the button below to launch the project in Gitpod.
If you are following along this tutorial locally, you will need to have the following setup on your machine:
It is also worth noting that currently CO2.js uses the Sustainable Web Design Model as the default when calculating carbon emissions. Check out the Methodologies for calculating website carbon page to learn more about both models.
If you are following along using the Gitpod starter template, you can skip this section.
Otherwise, create a new folder locally called co2js-node
and navigate into that folder. Then, initialise NPM.
mkdir co2js-node
cd co2js-node
npm init -y
Next, create an index.js
file, and open it in your code editor of choice. We will write the code for this tutorial inside the index.js
file.
Inside your project folder, run the following command to install CO2.js as a dependency.
npm install @tgwf/co2
In your project’s index.js
file, add the following code to initialise CO2.js.
const { co2 } = require("@tgwf/co2");
const co2Emission = new co2();
CO2.js includes a perByte()
function. This function accepts two variables:
number
- The bytes you want to calculate CO2 for.boolean
- Whether the bytes are transferred from a green host. By default, this value is false
.Adding the code below to the index.js
file allows us to calculate the carbon emissions of a gigabyte, transferred from a regular (not green) host.
const bytesSent = 1000 * 1000 * 1000; // 1GB expressed in bytes
const greenHost = false; // Is the data transferred from a green host?
estimatedCO2 = co2Emission.perByte(bytesSent, greenHost);
console.log(
`Sending a gigabyte, had a carbon footprint of ${estimatedCO2.toFixed(
3
)} grams of CO2`
);
In the code above, you are:
perByte
function, which returns a carbon estimate.To find out how much carbon 1GB of data produces, run the code in node.
node index.js
# Output:
# Sending a gigabyte, had a carbon footprint of 358.020 grams of CO2
You now know the carbon impact of a gigabyte.
From here you can:
bytesSent
variable.greenHost
variable to true
and see how green hosting effects carbon emissions.