From 9b864fc7f0c91fe83dda1cb4a3affd484e0ce65f Mon Sep 17 00:00:00 2001 From: Willie Ruemmele Date: Wed, 18 Sep 2024 11:50:04 -0600 Subject: [PATCH] chore: cache NodeFSTree read --- src/resolve/treeContainers.ts | 10 ++++++++-- test/resolve/treeContainers.test.ts | 15 +++++++++++++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/resolve/treeContainers.ts b/src/resolve/treeContainers.ts index eacefa46d6..38a470bfca 100644 --- a/src/resolve/treeContainers.ts +++ b/src/resolve/treeContainers.ts @@ -106,8 +106,14 @@ export class NodeFSTreeContainer extends TreeContainer { } public readFile(fsPath: SourcePath): Promise { - // significant enough performance increase using sync instead of fs.promise version - return Promise.resolve(readFileSync(fsPath)); + if (this.fileContentMap.has(fsPath)) { + return Promise.resolve(this.fileContentMap.get(fsPath)!); + } else { + // significant enough performance increase using sync instead of fs.promise version + const content = readFileSync(fsPath); + this.fileContentMap.set(fsPath, content); + return Promise.resolve(content); + } } public readFileSync(fsPath: SourcePath): Buffer { diff --git a/test/resolve/treeContainers.test.ts b/test/resolve/treeContainers.test.ts index 0bb7af61e9..e7136ba791 100644 --- a/test/resolve/treeContainers.test.ts +++ b/test/resolve/treeContainers.test.ts @@ -119,12 +119,23 @@ describe('Tree Containers', () => { it('should use expected Node API for readFileSync', () => { const readFileStub = env.stub(fs, 'readFileSync'); // @ts-ignore wants Dirents but string[] works as well - readFileStub.withArgs(path).returns(Buffer.from('test')); - const data = tree.readFileSync(path); + readFileStub.withArgs('myNewPath').returns(Buffer.from('test')); + const data = tree.readFileSync('myNewPath'); expect(data.toString()).to.deep.equal('test'); expect(readFileStub.calledOnce).to.be.true; }); + it('should use cached value for readFileSync', () => { + const readFileStub = env.stub(fs, 'readFileSync'); + // @ts-ignore wants Dirents but string[] works as well + readFileStub.withArgs('myNewPath').returns(Buffer.from('test')); + const data = tree.readFileSync('myNewPath'); + // returns same value + expect(data.toString()).to.deep.equal('test'); + // didn't re-read the file + expect(readFileStub.called).to.be.false; + }); + it('should use expected Node API for stream', () => { const readable = new Readable(); // @ts-ignore wants ReadStream but Readable works for testing