Skip to content
This repository has been archived by the owner on Apr 16, 2020. It is now read-only.

Commit

Permalink
esm: store json modules in CJS cache
Browse files Browse the repository at this point in the history
  • Loading branch information
MylesBorins committed Mar 6, 2019
1 parent 842ce61 commit d178e75
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/internal/modules/esm/translators.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,25 @@ translators.set('json', async (url) => {
debug(`Translating JSONModule ${url}`);
debug(`Loading JSONModule ${url}`);
const pathname = fileURLToPath(url);
const modulePath = isWindows ?
StringReplace(pathname, winSepRegEx, '\\') : pathname;
const module = CJSModule._cache[modulePath];
if (module && module.loaded) {
const exports = module.exports;
return createDynamicModule(['default'], url, (reflect) => {
reflect.exports.default.set(exports);
});
}
const content = await readFileAsync(pathname, 'utf-8');
return createDynamicModule(['default'], url, (reflect) => {
debug(`Parsing JSONModule ${url}`);
try {
const exports = JsonParse(stripBOM(content));
const module = {
exports,
loaded: true
};
CJSModule._cache[modulePath] = module;
reflect.exports.default.set(exports);
} catch (err) {
err.message = pathname + ': ' + err.message;
Expand Down
13 changes: 13 additions & 0 deletions test/es-module/test-esm-json-cache.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Flags: --experimental-modules --experimental-json-modules
/* eslint-disable node-core/required-modules */
import '../common/index.mjs';
import {strictEqual} from 'assert';

import mod from '../fixtures/es-modules/json-cache/mod.cjs';
import another from '../fixtures/es-modules/json-cache/another.cjs';
import test from '../fixtures/es-modules/json-cache/test.json';


strictEqual(mod.one, 1);
strictEqual(another.one, 'zalgo');
strictEqual(test.one, 'it comes');
7 changes: 7 additions & 0 deletions test/fixtures/es-modules/json-cache/another.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const test = require('./test.json');

module.exports = {
...test
};

test.one = 'it comes';
7 changes: 7 additions & 0 deletions test/fixtures/es-modules/json-cache/mod.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const test = require('./test.json');

module.exports = {
...test
}

test.one = 'zalgo';
5 changes: 5 additions & 0 deletions test/fixtures/es-modules/json-cache/test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"one": 1,
"two": 2,
"three": 3
}

0 comments on commit d178e75

Please sign in to comment.