Saif Bechan Saif Bechan - 5 months ago 10
Node.js Question

Casting string 'Infinity' to Infinity from dotenv file

I have a NodeJS app, and I am working on getting some config into a dotenv file. In my app I use a var

MAX_PAGES
which I set in local testing to 5 or something, but on production this var is set to
Infinity
.

When I use
Infinity
in my dotenv then I get the string
'Infinity'
.

I know I have other options such as:


  • using 999999999999999

  • Setting the dotenv var to -1 and if it is -1 in NodeJS I use Infinity

  • etc



Just wondering if a simple cast would be possible.

Answer

The easiest answer is eval(), but also the least safe:

eval('Infinity') // Infinity

But in your case Number() works just as well:

Number('Infinity') // Infinity

Alternatively, include a check:

if(MAX_PAGES === 'Infinity') MAX_PAGES = Infinity;
Comments