分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

.10-浅析webpack源码之graceful-fs模块

发布时间:2023-09-06 01:30责任编辑:彭小芳关键词:webpack

  在cachedInput、output、watch三大文件系统中,output非常简单,没有必要讲,其余两个模块依赖于input模块,而input主要是引用了graceful-fs的部分API,所以这节来讲讲graceful-fs。

  上一节整理的源码如下:

var fs = require(‘fs‘)// ...工具方法module.exports = patch(require(‘./fs.js‘))if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) { ???module.exports = patch(fs)}module.exports.close = fs.close = (function(fs$close) { /*...*/ })(fs.close)module.exports.closeSync = fs.closeSync = (function(fs$closeSync) { /*...*/ })(fs.closeSync)function patch(fs) { ???// fs方法二次封装 ???return fs}

  内容包含:

1、工具方法

2、patch引入的fs模块并输出

3、添加close/closeSync方法

util.debuglog

  首先看工具方法,代码如下:

var util = require(‘util‘);// 日志队列var queue = [];// debug函数var debug = noop;// 检测此方法是否存在并返回一个debug方法if (util.debuglog) ???debug = util.debuglog(‘gfs4‘);// 测试进程参数NODE_DEBUG是否包含‘gfs4‘else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ‘‘)) { ???// ?自定义一个debug函数 ???debug = (...args) => { ???????var m = util.format.apply(util, args); ???????m = ‘GFS4: ‘ + m.split(/\n/).join(‘\nGFS4: ‘); ???????console.error(m); ???}}if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ‘‘)) { ???// 监听退出事件 ???process.on(‘exit‘, function() { ???????// 批量输出日志内容 ???????debug(queue); ???????// 使用==测试参数是否相等 不等抛出error ???????require(‘assert‘).equal(queue.length, 0); ???})}

  这里会尝试调用util.debuglog来生成一个错误日志函数,每一次调用该函数会打印一条错误日志。

  在没有util.debuglog的情况下后自定义一个debug函数,测试代码如图:

const util = require(‘util‘);debug = (...args) => { ???var m = util.format.apply(util, args); ???m = ‘GFS4: ‘ + m.split(/\n/).join(‘\nGFS4: ‘); ???console.error(m);}debug(`log1log2log3`);

  执行后输出如图:

  这里可以顺便看一下nodejs中debuglog的源码,整理如下:

var debugs = {};// 收集所有DEBUG的环境名var debugEnviron;function debuglog(set) { ???if (debugEnviron === undefined) { ???????// 从NODE_DEBUG环境变量中收集所有的日志输出参数 ???????// 这里全部转为大写 ???????// 这就说明为什么debuglog传的是gfs4 输出的是GFS4 ???????debugEnviron = new Set( ???????????(process.env.NODE_DEBUG || ‘‘).split(‘,‘).map((s) => s.toUpperCase())); ???} ???set = set.toUpperCase(); ???// 没有该debuglog函数就创建一个 ???if (!debugs[set]) { ???????// 只对指定的参数进行输出 ???????if (debugEnviron.has(set)) { ???????????var pid = process.pid; ???????????debugs[set] = function() { ???????????????// 格式化参数信息 ???????????????var msg = exports.format.apply(exports, arguments); ???????????????// 依次输出:参数名 进程号 信息 ???????????????console.error(‘%s %d: %s‘, set, pid, msg); ???????????}; ???????} else { ???????????debugs[set] = function() {}; ???????} ???} ???return debugs[set];}

  可以看到,源码内部也是用console.error来进行错误日志输出,输出的格式比模拟方法多了一个进程号,基本上没啥区别。

  官网的实例我测不出来,先搁着,下面讲模块输出。

 模块输出‘./fs.js‘

  模块的输出有两个方式,取决的系统环境信息 TEST_GRACEFUL_FS_GLOBAL_PATCH ,这个参数可以设置,默认是undefined。

  若该值未设置,会调用本地的fs来进行patch,这个本地fs源码如下:

‘use strict‘var fs = require(‘fs‘)module.exports = clone(fs) ???// 拷贝对象function clone(obj) { ???if (obj === null || typeof obj !== ‘object‘) ???????return obj ???if (obj instanceof Object) ???????var copy = { __proto__: obj.__proto__ } ???else ???????var copy = Object.create(null) ???Object.getOwnPropertyNames(obj).forEach(function(key) { ???????Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) ???}) ???return copy}

  会深拷贝基本类型,但是对于复杂类型也只是浅拷贝,测试代码如下:

const a = { ???‘string‘: 1, ???‘arr‘: [1],}const b = clone(a);b.arr[0] = 2;b.string = 2;console.log(a); // {string:1,arr:[2]}const c = a;c.arr[0] = 3;c.string = 3;console.log(a); // {string:3,arr:[3]}

  总之,基本上相当于返回一个fs模块。

  无论如何,graceful-js都是输出patch后的fs模块,先不看同步/异步close,主要看patch方法是如何对原生API进行封装的,整理后源码如下:

function patch(fs) { ???// Everything that references the open() function needs to be in here ???// 跨平台兼容处理 ???polyfills(fs) ???fs.gracefulify = patch; ???// 遗留名字 ???fs.FileReadStream = ReadStream; // Legacy name. ???fs.FileWriteStream = WriteStream; // Legacy name. ???// 创建流 ???fs.createReadStream = createReadStream ???fs.createWriteStream = createWriteStream ???var fs$readFile = fs.readFile; ???fs.readFile = readFile; ???// 读取文件 ???function readFile(path, options, cb) { /*...*/ } ???var fs$writeFile = fs.writeFile; ???fs.writeFile = writeFile; ???// 写文件 ???function writeFile(path, data, options, cb) { /*...*/ } ???var fs$appendFile = fs.appendFile; ???if (fs$appendFile) ???????fs.appendFile = appendFile; ???// 文件添加内容 ???function appendFile(path, data, options, cb) { /*...*/ } ???var fs$readdir = fs.readdir; ???fs.readdir = readdir; ???// 读取目录 ???function readdir(path, options, cb) { /*...*/ } ???function go$readdir(args) { /*...*/ } ???if (process.version.substr(0, 4) === ‘v0.8‘) { /*...*/ } ???// 流处理 ???// 可读的流 ???var fs$ReadStream = fs.ReadStream; ???ReadStream.prototype = Object.create(fs$ReadStream.prototype); ???ReadStream.prototype.open = ReadStream$open; ???// 可写的流 ???var fs$WriteStream = fs.WriteStream; ???WriteStream.prototype = Object.create(fs$WriteStream.prototype); ???WriteStream.prototype.open = WriteStream$open; ???fs.ReadStream = ReadStream ???fs.WriteStream = WriteStream ???function ReadStream(path, options) { /*...*/ } ???function ReadStream$open() { /*...*/ } ???function WriteStream(path, options) { /*...*/ } ???function WriteStream$open() { /*...*/ } ???function createReadStream(path, options) { /*...*/ } ???function createWriteStream(path, options) { /*...*/ } ???var fs$open = fs.open; ???fs.open = open; ???// 以某种形式打开文件 ???function open(path, flags, mode, cb) { /*...*/ } ???return fs}

  基本上文件操作API均有涉及,兼容处理这里不讨论。

  tips:以fs$***开头的变量均为原生API,例如fs$readFile代表原生的fs.readFile

  tips:源码有些写法真的僵硬,进行了一些优化增加可读性

  功能主要分为下列几块:

1、读取文件全部内容

2、写入数据到文件

3、向文件添加数据

4、读取目录

5、打开文件

6、流相关

  依次进行讲解。

文件读取:readFile

  前面说的代码优化包含尽量用ES6简写,先上下源代码:

  强行给函数加个名字,go你个头,修改后源码如下:

function readFile(path, options, cb) { ???// options参数可选 ???// 若第二参数为函数 代表省略了options参数 ???if (typeof options === ‘function‘) ???????cb = options, options = null; ???// 调用原生的fs.readFile ???return go$readFile(path, options, cb) ???function go$readFile(path, options, cb) { ???????return fs$readFile(path, options, function(err) { ???????????// 如果出错记录下来 ???????????if (err && (err.code === ‘EMFILE‘ || err.code === ‘ENFILE‘)) { ???????????????// 分别为fs模块类型 参数 ???????????????enqueue([go$readFile, [path, options, cb]]) ???????????} else { ???????????????if (typeof cb === ‘function‘) ???????????????????cb.apply(this, arguments) ???????????????retry() ???????????} ???????}) ???}}// 记录错误function enqueue(elem) { ???debug(‘ENQUEUE‘, elem[0].name, elem[1]) ???queue.push(elem)}// 重试之前产生报错的行为function retry() { ???var elem = queue.shift() ???if (elem) { ???????debug(‘RETRY‘, elem[0].name, elem[1]) ???????elem[0].apply(null, elem[1]) ???}}

  总结一下graceful-fs的优雅行为:

1、底层仍然调用的是nodejs原生API

2、当某个fs行为出错,该fs操作类型与参数会被记录下来

3、当某个fs行为成功执行,会尝试将最早出错的行为取出并再次执行,出错会再次被记录

  其余方法诸如writeFile、appendFile、readdir均与此类似,而流的抽象接口也并没有做什么额外操作,只是对读写操作中的open进行了上述加工,这里就不进行讲解了。

close/closeSync

  这两个方法用了大量注释,我还以为有啥特殊功能,代码如下:

// Always patch fs.close/closeSync, because we want to// retry() whenever a close happens *anywhere* in the program.// This is essential when multiple graceful-fs instances are// in play at the same time.module.exports.close = ???fs.close = (function(fs$close) { ???????return function(fd, cb) { ???????????return fs$close.call(fs, fd, function(err) { ???????????????// 关闭之前进行重试一次 ???????????????if (!err) ???????????????????retry() ???????????????if (typeof cb === ‘function‘) ???????????????????cb.apply(this, arguments) ???????????}) ???????} ???})(fs.close)module.exports.closeSync = ???fs.closeSync = (function(fs$closeSync) { ???????return function(fd) { ???????????// Note that graceful-fs also retries when fs.closeSync() fails. ???????????// Looks like a bug to me, although it‘s probably a harmless one. ???????????var rval = fs$closeSync.apply(fs, arguments) ???????????retry() ???????????return rval ???????} ???})(fs.closeSync)

  其实这里的注释还是蛮有味道的,尤其是下面的closeSync,第一次见源码注释带有作者第一人称的特殊解释(me)

  至此,grace-ful模块解析完成,其实内容并没有多复杂。

.10-浅析webpack源码之graceful-fs模块

原文地址:http://www.cnblogs.com/QH-Jimmy/p/8043466.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved