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

Commit

Permalink
Merge pull request #126 from keithamus/cache-reads
Browse files Browse the repository at this point in the history
perf: cache file stats/reads
  • Loading branch information
keithamus authored Mar 7, 2018
2 parents 848c371 + 313a3e3 commit f65152d
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,34 @@ 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;
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 Down Expand Up @@ -37,6 +65,11 @@ export default function nodeResolve ( options = {} ) {
preserveSymlinks = options.preserveSymlinks;
},

onwrite () {
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 @@ -91,7 +124,7 @@ export default function nodeResolve ( options = {} ) {
return browser;
}, {});
}

if (options.browser && typeof pkg[ 'browser' ] === 'string') {
pkg[ 'main' ] = pkg[ 'browser' ];
} else if ( useModule && pkg[ 'module' ] ) {
Expand All @@ -103,6 +136,8 @@ export default function nodeResolve ( options = {} ) {
}
return pkg;
},
readFile: cachedReadFile,
isFile: cachedIsFile,
extensions: options.extensions
};

Expand Down

0 comments on commit f65152d

Please sign in to comment.