当前位置:网站首页>浅读一下dotenv的主干逻辑的源码
浅读一下dotenv的主干逻辑的源码
2022-08-02 21:47:00 【lazytomato】
start
- 前面学习了 process.env
- 有用到 这么一个插件:
dotenv - 看一下
dotenv的源码
之前如何使用的?
let a = require('dotenv').config()
console.log(process.env.a)
开始
- 下载
npm i dotenv
直奔主题
- package.json
- main 属性对应的文件

阅读源码
main.js
const fs = require('fs')
const path = require('path')
const os = require('os')
const LINE =
/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm
// Parser src into an Object 解析src为一个对象
function parse(src) {
const obj = {
}
// Convert buffer to string
let lines = src.toString()
// Convert line breaks to same format
lines = lines.replace(/\r\n?/gm, '\n')
let match
while ((match = LINE.exec(lines)) != null) {
const key = match[1]
// Default undefined or null to empty string
let value = match[2] || ''
// Remove whitespace
value = value.trim()
// Check if double quoted
const maybeQuote = value[0]
// Remove surrounding quotes
value = value.replace(/^(['"`])([\s\S]*)\1$/gm, '$2')
// Expand newlines if double quoted
if (maybeQuote === '"') {
value = value.replace(/\\n/g, '\n')
value = value.replace(/\\r/g, '\r')
}
// Add to object
obj[key] = value
}
return obj
}
function _log(message) {
console.log(`[dotenv][DEBUG] ${
message}`)
}
function _resolveHome(envPath) {
return envPath[0] === '~'
? path.join(os.homedir(), envPath.slice(1))
: envPath
}
// Populates process.env from .env file 从文件 .env 向 process.env 添加数据
function config(options) {
// 1. 获取当前进程执行的路径对应的 .env文件
let dotenvPath = path.resolve(process.cwd(), '.env')
// 2. 定义编码格式
let encoding = 'utf8'
const debug = Boolean(options && options.debug)
const override = Boolean(options && options.override)
// 3. 接受一些参数,用来修改路径和编码格式
if (options) {
if (options.path != null) {
dotenvPath = _resolveHome(options.path)
}
if (options.encoding != null) {
encoding = options.encoding
}
}
try {
// Specifying an encoding returns a string instead of a buffer 指定编码返回一个字符串而不是一个缓冲区
// 4. 这里读取了文件,返回的字符串,通过 parse 将字符串转换为对象
const parsed = DotenvModule.parse(fs.readFileSync(dotenvPath, {
encoding }))
// 5. 遍历返回的对象的 key 分别添加到 process.env 中
Object.keys(parsed).forEach(function (key) {
if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
process.env[key] = parsed[key]
} else {
// 是否重写原型上的属性
if (override === true) {
process.env[key] = parsed[key]
}
// debug模式
if (debug) {
if (override === true) {
_log(
`"${
key}" is already defined in \`process.env\` and WAS overwritten`
)
} else {
_log(
`"${
key}" is already defined in \`process.env\` and was NOT overwritten`
)
}
}
}
})
// 6. 返回值是 { parsed:parsed } 这里简写了。
return {
parsed }
} catch (e) {
if (debug) {
_log(`Failed to load ${
dotenvPath} ${
e.message}`)
}
return {
error: e }
}
}
const DotenvModule = {
config,
parse,
}
module.exports.config = DotenvModule.config
module.exports.parse = DotenvModule.parse
module.exports = DotenvModule
总结
源码也就 100 多行
- 读取 .env 文件
- 将读取的内容转换成对象
- 遍历读取到的对象,将属性绑定到
process.env上
没啥难度,可能就是正则写的人看不懂。。。。
边栏推荐
- 博客主题美化第二弹
- 嗨!不来看一下如何骚气十足的登陆MySQL嘛?
- 总数据量超万亿行,玉溪卷烟厂通过正确选择时序数据库轻松应对
- You and I will meet the needs of: how to export the data in a MySQL simple ~!Practical!
- JS Date 时间戳 getTune data.parse 倒计时小程序
- 如何抓住NFT、元|宇|宙新趋势?
- 【DEBUG】ImportError: Unable to import required dependencies: numpy: DLL load failed: 找不到指定的模块。
- MySQL 用id分库使用name查询
- 快速学会ansible的安装
- @Transactional 事务调用与生效场景总结
猜你喜欢
随机推荐
go os 包
增删改查这么多年,最后栽在MySQL的架构设计上!
ML之PDP:基于titanic泰坦尼克是否获救二分类预测数据集利用PDP部分依赖图对RF随机森林和LightGBM模型实现可解释性案例
word操作:单独调整英文字体
go context 包
无线振弦采集仪远程修改参数的方式
go 反射 reflect 包
I interviewed a 985 graduate, and I will never forget the expression when answering the "performance tuning" question
典型相关分析CCA计算过程
网络运维系列:健康检查的方式
SRv6网络演进面临的挑战
若依集成minio实现分布式文件存储
【STM32学习3】DMA基础操作
go 序列化与反序列化
工厂模式理解了没有?
第十章 时序与延迟
命令行启动常见问题及解决方案
RuoYi-App Startup Tutorial
js函数防抖和函数节流及其他使用场景
Zabbix 5.0 Monitoring Tutorial (2)









