Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

require of JSON returns empty object #7

Open
zbysekmartoch opened this issue Jan 30, 2017 · 2 comments
Open

require of JSON returns empty object #7

zbysekmartoch opened this issue Jan 30, 2017 · 2 comments
Labels

Comments

@zbysekmartoch
Copy link

On the line 73 is called _compile() and it results into empty object when the content of required module is JSON. I changed my code and assign result of JSON.parse() directly to exports, if extension is '.json'. I'm not sure if it is correct fix and maybe it brings other issues.

@bahmutov
Copy link
Owner

Hmm, do you hook to .js object or to .json object?

hook.hook('.js', logLoadedFilename)
// should only process .js files

If you want JSON files, see example in https://glebbahmutov.com/blog/hooking-into-node-loader-for-fun-and-profit/#strip-c-style-comments-from-json-files

@zbysekmartoch
Copy link
Author

I hook to both
hook.hook('.js', logLoadedFilename);
hook.hook('.json', logLoadedFilename);

and even if I do nothing with the source, e.g.

function logLoadedFilename(source, filename) {
    return source;
}

running of the script fails. I've digged into and realised, that one require of json file returns empty object. I stepped into your hook function and . . .

#72 if (typeof ret === 'string') {   // JSON string is in ret, so everything is ok
#73      module._compile(ret, filename);  // empty obj is in ret
#74 } else ...

I hot fixed it like this


if (typeof ret === 'string') {
      if (extension=='.js') {
          module._compile(ret, filename);
      } else {
          module.exports=JSON.parse(source);
      }
} else ... 

Module hooking is amazing fun, and thank you for introduction in it. Now I'm experimenting with lower level of it, with fs.readFileSync hooking :-)

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants