Skip to content

Commit

Permalink
module: optimize js and json file i/o
Browse files Browse the repository at this point in the history
Use internalModuleReadFile() to read the file from disk to avoid the
fs.fstatSync() call that fs.readFileSync() makes.

It does so to know the file size in advance so it doesn't have to
allocate O(n) buffers when reading the file from disk.

internalModuleReadFile() is plenty efficient though, even more so
because we want a string and not a buffer.  This way we also don't
allocate a buffer that immediately gets thrown away again.

This commit reduces the number of fstat() system calls in a benchmark
application[0] from 549 to 29, all made by the application itself.

[0] https://github.com/strongloop/loopback-sample-app

PR-URL: nodejs#4575
Reviewed-By: Colin Ihrig <[email protected]>
Reviewed-By: James M Snell <[email protected]>
  • Loading branch information
bnoordhuis authored and jasnell committed Jan 12, 2016
1 parent 038b636 commit 7c60328
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -428,14 +428,14 @@ Module.prototype._compile = function(content, filename) {

// Native extension for .js
Module._extensions['.js'] = function(module, filename) {
var content = fs.readFileSync(filename, 'utf8');
var content = internalModuleReadFile(filename);
module._compile(internalModule.stripBOM(content), filename);
};


// Native extension for .json
Module._extensions['.json'] = function(module, filename) {
var content = fs.readFileSync(filename, 'utf8');
var content = internalModuleReadFile(filename);
try {
module.exports = JSON.parse(internalModule.stripBOM(content));
} catch (err) {
Expand Down

0 comments on commit 7c60328

Please sign in to comment.