当前位置:网站首页>浅读一下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
上
没啥难度,可能就是正则写的人看不懂。。。。
边栏推荐
- go exec 包
- 【TypeScript】深入学习TypeScript类(下)
- 同样月薪6K,为什么同事跳槽月薪翻倍,而你只涨了1000?
- RuoYi-App Startup Tutorial
- FRED应用:激光二极管光源耦合到光纤的仿真
- Intensive reading of the Swin Transformer paper and analysis of its model structure
- How many ways do you know the singleton pattern?
- iptables、firewalld的使用
- Software testing pen questions 1 (with answers)
- H5网页播放器EasyPlayer.js播放器界面的加载效果无法消失是什么原因?
猜你喜欢
测试ESP32-Zigbee转发命令 : 滑轨、继电器控制
牛客每日刷题之链表
ML之PDP:基于titanic泰坦尼克是否获救二分类预测数据集利用PDP部分依赖图对RF随机森林和LightGBM模型实现可解释性案例
The only way to go from a monthly salary of 10k to 30k: automated testing
LeetCode 2359. 找到离给定两个节点最近的节点 基环树
Learn more TypeScript 】 【 TypeScript modular
Auto.js脚本程序打包
TDengine 在中天钢铁 GPS、 AIS 调度中的落地
微软SQL服务器被黑客入侵以窃取代理服务的带宽
If the watermark according to how to realize the function
随机推荐
MySQL 用id分库使用name查询
Add and delete all these years, finally planted in MySQL architecture design!
What is the core business model of the "advertising e-commerce" that has recently become popular in the circle of friends, and is the advertising revenue really reliable?
Command line startup FAQs and solutions
不堪哥哥殴打谩骂,妹妹申请人身安全保护令获支持
Abstract Factory Pattern
从月薪10k到30k的必走之路:自动化测试
采用QT进行OpenGL开发(三)着色器编程
搭建Spark开发环境(第二弹)
UDP (User Datagram Protocol)
Do you understand the factory pattern?
js函数防抖和函数节流及其他使用场景
2022-08-02 第六小组 瞒春 学习笔记
H.265视频流媒体播放器EasyPlayer.js集成时出现“SourceBuffer ”报错,该如何解决?
第十章 时序与延迟
【使用pyside2遇到的问题】This application failed to start because no Qt platform plugin could be initialized.
JumpServer开源堡垒机完成龙芯架构兼容性认证
以赛促练-力扣第304场周赛反思(持续更新中)
你我都会遇到的需求:如何导出MySQL中的数据~ 简单!实用!
刚安装完win10专业工作站版,系统变量中Path默认值有哪些?重新建一个“PATH”变量名,会覆盖掉原先的“Path”。