当我运行
npx tsx
时,我得到一个 REPL,它让我可以像这样需要模块:
> const dotenv = require('dotenv');
> dotenv.config({ path: './config/env' }); // There's an index file in the env directory.
以上两个命令的输出如下:
{
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'
}
}
但是当我调用
dotenv.config({ path: './config/env/index.ts' });
时,我没有得到包含派生或计算属性或任何环境变量的预期输出。相反,我看到了这个:
{
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,'
}
}
正如您所想象的,这并不完全理想,因为我的
root
属性没有被计算,fileSizeLimit
也没有被计算。有没有办法使用 dotenv 在 tsx REPL 中创建配置?
因此,将环境变量放入 tsx REPL 的方法是:
> const dotenv = require('dotenv');
> const config = dotenv.config({ path: './.env.development' });
> config.parsed.EMAIL
'[email protected]'
> process.env.EMAIL
'[email protected]'
现在这些可用于设置猫鼬连接到经过身份验证的数据库或存储您不想输入的各种其他秘密。这就是在 tsx REPL 中使用 dotenv 的方法。