node.jsenvironment-variablesjimp

NodeJS: Use Data in Raw Format from .env


I have the following code which uses Jimp package to edit the background of a file:

const file = await Jimp.read(JPGPath)
  file
    .resize(parseInt(width), parseInt(height))
    .background(process.env.JPG_BACKGROUND_COLOR)
    .write(JPGPath)

Anytime I run this code, I get an error from Jimp saying: Error: hex must be a hexadecimal rgba value"

The value of JPG_BACKGROUND_COLOR in .env is 0xFFFFFFFF which is a correct hexadecimal rgba value for Jimp

So the code works whenever i use the JPG_BACKGROUND_COLOR value directly like this:

const file = await Jimp.read(JPGPath)
  file
    .resize(parseInt(width), parseInt(height))
    .background(0xFFFFFFFF)
    .write(JPGPath)

How can I make the first code to work because i need to set the JPG_BACKGROUND_COLOR in .env

Note: console.log(process.env.JPG_BACKGROUND_COLOR) prints 0xFFFFFFFF so the value is not empty, but it is parsed to string whereas Jimp doesn't accept strings so how do i pass the value from .env raw into the Jimp package


Solution

  • You can use dotenv package to load variables from .env file.

    As early as possible in your application, require and configure dotenv.

    require('dotenv').config()
    

    it will be enough for you. updated:

    please use parseInt

    file
        .resize(parseInt(width), parseInt(height))
        .background(parseInt(process.env.JPG_BACKGROUND_COLOR))
        .write(JPGPath)