Skip to content
This repository was archived by the owner on Aug 4, 2021. It is now read-only.

Commit f65152d

Browse files
authored
Merge pull request #126 from keithamus/cache-reads
perf: cache file stats/reads
2 parents 848c371 + 313a3e3 commit f65152d

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

src/index.js

+36-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,34 @@ const ES6_BROWSER_EMPTY = resolve( __dirname, '../src/empty.js' );
88
const CONSOLE_WARN = ( ...args ) => console.warn( ...args ); // eslint-disable-line no-console
99
const exts = [ '.js', '.json', '.node' ];
1010

11+
let readFileCache = {};
12+
const readFileAsync = file => new Promise((fulfil, reject) => fs.readFile(file, (err, contents) => err ? reject(err) : fulfil(contents)));
13+
const statAsync = file => new Promise((fulfil, reject) => fs.stat(file, (err, contents) => err ? reject(err) : fulfil(contents)));
14+
function cachedReadFile (file, cb) {
15+
if (file in readFileCache === false) {
16+
readFileCache[file] = readFileAsync(file).catch(err => {
17+
delete readFileCache[file];
18+
throw err;
19+
});
20+
}
21+
readFileCache[file].then(contents => cb(null, contents), cb);
22+
}
23+
24+
let isFileCache = {};
25+
function cachedIsFile (file, cb) {
26+
if (file in isFileCache === false) {
27+
isFileCache[file] = statAsync(file)
28+
.then(
29+
stat => stat.isFile(),
30+
err => {
31+
if (err.code == 'ENOENT') return false;
32+
delete isFileCache[file];
33+
throw err;
34+
});
35+
}
36+
isFileCache[file].then(contents => cb(null, contents), cb);
37+
}
38+
1139
export default function nodeResolve ( options = {} ) {
1240
const useModule = options.module !== false;
1341
const useMain = options.main !== false;
@@ -37,6 +65,11 @@ export default function nodeResolve ( options = {} ) {
3765
preserveSymlinks = options.preserveSymlinks;
3866
},
3967

68+
onwrite () {
69+
isFileCache = {};
70+
readFileCache = {};
71+
},
72+
4073
resolveId ( importee, importer ) {
4174
if ( /\0/.test( importee ) ) return null; // ignore IDs with null character, these belong to other plugins
4275

@@ -91,7 +124,7 @@ export default function nodeResolve ( options = {} ) {
91124
return browser;
92125
}, {});
93126
}
94-
127+
95128
if (options.browser && typeof pkg[ 'browser' ] === 'string') {
96129
pkg[ 'main' ] = pkg[ 'browser' ];
97130
} else if ( useModule && pkg[ 'module' ] ) {
@@ -103,6 +136,8 @@ export default function nodeResolve ( options = {} ) {
103136
}
104137
return pkg;
105138
},
139+
readFile: cachedReadFile,
140+
isFile: cachedIsFile,
106141
extensions: options.extensions
107142
};
108143

0 commit comments

Comments
 (0)