Skip to content

Commit 9b864fc

Browse files
chore: cache NodeFSTree read
1 parent 969c2e4 commit 9b864fc

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

src/resolve/treeContainers.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,14 @@ export class NodeFSTreeContainer extends TreeContainer {
106106
}
107107

108108
public readFile(fsPath: SourcePath): Promise<Buffer> {
109-
// significant enough performance increase using sync instead of fs.promise version
110-
return Promise.resolve(readFileSync(fsPath));
109+
if (this.fileContentMap.has(fsPath)) {
110+
return Promise.resolve(this.fileContentMap.get(fsPath)!);
111+
} else {
112+
// significant enough performance increase using sync instead of fs.promise version
113+
const content = readFileSync(fsPath);
114+
this.fileContentMap.set(fsPath, content);
115+
return Promise.resolve(content);
116+
}
111117
}
112118

113119
public readFileSync(fsPath: SourcePath): Buffer {

test/resolve/treeContainers.test.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,12 +119,23 @@ describe('Tree Containers', () => {
119119
it('should use expected Node API for readFileSync', () => {
120120
const readFileStub = env.stub(fs, 'readFileSync');
121121
// @ts-ignore wants Dirents but string[] works as well
122-
readFileStub.withArgs(path).returns(Buffer.from('test'));
123-
const data = tree.readFileSync(path);
122+
readFileStub.withArgs('myNewPath').returns(Buffer.from('test'));
123+
const data = tree.readFileSync('myNewPath');
124124
expect(data.toString()).to.deep.equal('test');
125125
expect(readFileStub.calledOnce).to.be.true;
126126
});
127127

128+
it('should use cached value for readFileSync', () => {
129+
const readFileStub = env.stub(fs, 'readFileSync');
130+
// @ts-ignore wants Dirents but string[] works as well
131+
readFileStub.withArgs('myNewPath').returns(Buffer.from('test'));
132+
const data = tree.readFileSync('myNewPath');
133+
// returns same value
134+
expect(data.toString()).to.deep.equal('test');
135+
// didn't re-read the file
136+
expect(readFileStub.called).to.be.false;
137+
});
138+
128139
it('should use expected Node API for stream', () => {
129140
const readable = new Readable();
130141
// @ts-ignore wants ReadStream but Readable works for testing

0 commit comments

Comments
 (0)