Skip to content
This repository was archived by the owner on Aug 4, 2021. It is now read-only.
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 6ccdb4f

Browse files
committedFeb 20, 2018
perf: cache file stats/reads
1 parent 902c848 commit 6ccdb4f

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
 

‎src/index.js

+34
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,33 @@ 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(stat => stat.isFile())
29+
.catch(err => {
30+
if (err.code == 'ENOENT') return false;
31+
delete isFileCache[file];
32+
throw err;
33+
});
34+
}
35+
isFileCache[file].then(contents => cb(null, contents), cb);
36+
}
37+
1138
export default function nodeResolve ( options = {} ) {
1239
const useModule = options.module !== false;
1340
const useMain = options.main !== false;
@@ -31,6 +58,11 @@ export default function nodeResolve ( options = {} ) {
3158
return {
3259
name: 'node-resolve',
3360

61+
write () {
62+
isFileCache = {}
63+
readFileCache = {}
64+
},
65+
3466
resolveId ( importee, importer ) {
3567
if ( /\0/.test( importee ) ) return null; // ignore IDs with null character, these belong to other plugins
3668

@@ -99,6 +131,8 @@ export default function nodeResolve ( options = {} ) {
99131
}
100132
return pkg;
101133
},
134+
readFile: cachedReadFile,
135+
isFile: cachedIsFile,
102136
extensions: options.extensions
103137
}, customResolveOptions ),
104138
( err, resolved ) => {

0 commit comments

Comments
 (0)
This repository has been archived.