.10-淺析webpack源碼之graceful-fs模塊

来源:http://www.cnblogs.com/QH-Jimmy/archive/2017/12/16/8043466.html
-Advertisement-
Play Games

在cachedInput、output、watch三大文件系統中,output非常簡單,沒有必要講,其餘兩個模塊依賴於input模塊,而input主要是引用了graceful-fs的部分API,所以這節來講講graceful-fs。 上一節整理的源碼如下: 內容包含: 1、工具方法 2、patch引 ...


  在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');// 檢測此方法是否存在並返回一個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(`log1
log2
log3`);

  執行後輸出如圖:

  這裡可以順便看一下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

  源碼如下:

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模塊解析完成,其實內容並沒有多複雜。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...