From 7c603280024de60329d5da283fb8433420bc6716 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Fri, 8 Jan 2016 10:40:32 +0100 Subject: [PATCH] module: optimize js and json file i/o 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: https://github.com/nodejs/node/pull/4575 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- lib/module.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/module.js b/lib/module.js index a068bffa7d9056..ca2c805bb0da16 100644 --- a/lib/module.js +++ b/lib/module.js @@ -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) {