0

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

Israel Obanijesu
  • 666
  • 1
  • 12
  • 24
  • please check if your env variable has value by printing it, i think you env variables are not loading. – salman Oct 14 '20 at 08:15
  • There is a really usefull package `dotenv`: it parses a .env file and stores the values in `process.env.VARIABLE_NAME` – Hollyol Oct 14 '20 at 08:15
  • @israel-obanijesu [This](https://stackoverflow.com/questions/22312671/setting-environment-variables-for-node-to-retrieve) should help – Hollyol Oct 14 '20 at 08:25
  • It is loading @salman and Hollyol, i already printed it, but the problem is the data format is in string, it needs to be raw not string – Israel Obanijesu Oct 14 '20 at 10:03
  • @IsraelObanijesu please check my answer. – salman Oct 14 '20 at 11:37

2 Answers2

1

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)
salman
  • 264
  • 1
  • 9
0

load dot env file package and then import it