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

Commit

Permalink
perf: cache file stats/reads
Browse files Browse the repository at this point in the history
  • Loading branch information
keithamus committed Feb 20, 2018
1 parent 902c848 commit 0c3689c
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,37 @@ const ES6_BROWSER_EMPTY = resolve( __dirname, '../src/empty.js' );
const CONSOLE_WARN = ( ...args ) => console.warn( ...args ); // eslint-disable-line no-console
const exts = [ '.js', '.json', '.node' ];

let readFileCache = {};
const readFileAsync = file => new Promise((fulfil, reject) => fs.readFile(file, (err, contents) => err ? reject(err) : fulfil(contents)));
const statAsync = file => new Promise((fulfil, reject) => fs.stat(file, (err, contents) => err ? reject(err) : fulfil(contents)));
function cachedReadFile (file, cb) {
if (file in readFileCache === false) {
readFileCache[file] = readFileAsync(file).catch(err => {
delete readFileCache[file];
throw err;
});
}
readFileCache[file].then(contents => cb(null, contents), cb);
}

let isFileCache = {};
function cachedIsFile (file, cb) {
if (file in isFileCache === false) {
isFileCache[file] = statAsync(file)
.then(
stat => stat.isFile(),
err => {
if (err.code == 'ENOENT') return false;
throw err;
}
).catch(err => {
delete isFileCache[file];
throw err;
});
}
isFileCache[file].then(contents => cb(null, contents), cb);
}

export default function nodeResolve ( options = {} ) {
const useModule = options.module !== false;
const useMain = options.main !== false;
Expand All @@ -31,6 +62,11 @@ export default function nodeResolve ( options = {} ) {
return {
name: 'node-resolve',

write () {
isFileCache = {}
readFileCache = {}
},

resolveId ( importee, importer ) {
if ( /\0/.test( importee ) ) return null; // ignore IDs with null character, these belong to other plugins

Expand Down Expand Up @@ -99,6 +135,8 @@ export default function nodeResolve ( options = {} ) {
}
return pkg;
},
readFile: cachedReadFile,
isFile: cachedIsFile,
extensions: options.extensions
}, customResolveOptions ),
( err, resolved ) => {
Expand Down

0 comments on commit 0c3689c

Please sign in to comment.