Skip to content

Instantly share code, notes, and snippets.

@ccgus ccgus/nodestyle.m
Created May 13, 2019

Embed
What would you like to do?
- (FJSValue*)evaluateModuleAtURL:(NSURL*)scriptURL {
if (scriptURL) {
NSError *error;
NSString *script = [NSString stringWithContentsOfURL:scriptURL encoding:NSUTF8StringEncoding error:&error];
if (script) {
#define NODE_STYLE_WRAPPER 1
#ifdef NODE_STYLE_WRAPPER
NSString *moduleWrapper = @"(function(__filename, __dirname) {\nvar module = { exports : {} }; var exports = module.exports;\n%@;\nreturn module.exports;})";
moduleWrapper = [NSString stringWithFormat:moduleWrapper, script];
FJSValue *moduleValueFunction = [self evaluateNoQueue:moduleWrapper withSourceURL:scriptURL];
FJSValue *moduleValue = [moduleValueFunction callWithArguments:@[[scriptURL path], [[scriptURL URLByDeletingLastPathComponent] path]]];
#else
id fn = self[@"__filename"];
id dn = self[@"__dirname"];
// __filename and __dirname are node things. I wish we could pass them in as arguments, but I can't seem to massage the js so that'll happen.
self[@"__filename"] = [scriptURL path];
self[@"__dirname"] = [[scriptURL URLByDeletingLastPathComponent] path];
NSString *module = [NSString stringWithFormat:@"(function() { var module = { exports : {} }; var exports = module.exports; %@;\nreturn module.exports; })()", script];
FJSValue *moduleValue = [self evaluateNoQueue:module withSourceURL:scriptURL];
self[@"__filename"] = [fn isUndefined] || [fn isNull] ? nil : fn;
self[@"__dirname"] = [dn isUndefined] || [dn isNull] ? nil : dn;
#endif
return moduleValue;
}
else if (error) {
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"Cannot find module %@", scriptURL.path] userInfo:nil];
}
}
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.