node.jstypescriptread-eval-print-loopdotenvnode-tsx

How do I use dotenv with the tsx REPL for typescript?


When I run npx tsx, I get a REPL that lets me require modules like so:

> const dotenv = require('dotenv');
> dotenv.config({ path: './config/env' }); // There's an index file in the env directory.

The output of the above two commands is below:

{
  error: Error: EISDIR: illegal operation on a directory, read
      at Object.readSync (node:fs:749:3)
      at tryReadSync (node:fs:449:20)
      at Object.readFileSync (node:fs:495:19)
      at Object.configDotenv (/server/node_modules/dotenv/lib/main.js:198:42)
      at Object.config (server/node_modules/dotenv/lib/main.js:223:25)
      at REPL2:1:8
      at Script.runInThisContext (node:vm:129:12)
      at REPLServer.defaultEval (node:repl:572:29)
      at bound (node:domain:433:15)
      at REPLServer.runBound (node:domain:444:12) {
    errno: -21,
    syscall: 'read',
    code: 'EISDIR'
  }
}

But when I call dotenv.config({ path: './config/env/index.ts' }); I do not get the expected output containing derived or computed properties, or any env variables. Instead, I see this:

{
 parsed: {
    root: "path.join(path.dirname('.'), '/..'),",
    api: '{',
    title: "'API: Users and Application Resources',",
    version: "'0.0.1',",
    description: "'A RESTful API for managing users and application resources.',",
    fileSizeLimit: '10 * 1024 * 1024,'
  }
}

As you can imagine, this isn't exactly ideal given that my root property wasn't computed, and nor was fileSizeLimit. Is there a way to use dotenv to create a configuration in the tsx REPL?


Solution

  • So the way to get your environment variables into the tsx REPL is to:

    > const dotenv = require('dotenv');
    > const config = dotenv.config({ path: './.env.development' });
    > config.parsed.EMAIL
    'myemail@test.example.com'
    > process.env.EMAIL
    'myemail@test.example.com'
    

    Now these can be used to set up a mongoose connect to an authenticated database or store various other secrets you'd rather not type out. So that's how to use dotenv in the tsx REPL.