Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

require()'ing json from a relative path inside runSync #2

Closed
bigblind opened this issue Feb 23, 2015 · 2 comments
Closed

require()'ing json from a relative path inside runSync #2

bigblind opened this issue Feb 23, 2015 · 2 comments

Comments

@bigblind
Copy link

I have a function that looks as follows:

getConfig: function(key){
    return atcompile.runSync(function(){
        return require("./../../config/settings.json")[key];
    });
}

but it keeps telling me that the module ./../../config/settings.json doesn't exist.

In the source of runSync, I see that you're passing a require wrapper into the context, but I don't know how to make it resolve relative paths correctly.

@brigand
Copy link
Owner

brigand commented Feb 24, 2015

The require() problem is a temporary limitation (I still need to find a decent solution). You can work around it by using fs.readFileSync and JSON.parse.

Because it runs the function at compile time, there's no way for it to use runtime variables like the key argument.

What you can do, currently, is this:

var config = atcompile.runSync(function(){
  var read = require('fs').readFileSync;
  var settings = JSON.parse(read('config/settings.json', 'utf8'));

  // whitelist some keys, or you can just return the whole thing
  return {
    foo: settings.foo,
    bar: setting.bar
  };
});

// if you still want the getConfig api
exports.getConfig = function(key){
    return config[key];
}

And this ends up like this:

var config = {"foo": {"...":"..."}, "bar": 7};

If you prefer to not do this, you can create your own transform using static-module, which basically just lets you inline function calls (it's what atcompileify, brfs, etc. use).

@bigblind
Copy link
Author

Cool, I'll take a look at static-module.

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

No branches or pull requests

2 participants