you can use

1) "load" from object - object with name and script properties.

2) or use 'eval' naming // #sourceURL comment

as mentioned here:

http://mail.openjdk.java.net/pipermail/nashorn-dev/2014-July/003174.html

Can code for body of module function be something like "eval(readScriptAsText() + "\n// #sourceURL=" + name)" ?

Hope this helps,
-Sundar

On Wednesday 18 February 2015 03:30 PM, Tim Fox wrote:
I've added a simple reproducer that you can run in the repl:

https://gist.github.com/purplefox/b03a2a6263c26e3206da

Another observation is that line number is reported as 6, when it should be 5 (assuming the first line is line 1 which is normal convention afaik)

On 18/02/15 09:40, Tim Fox wrote:
Hi all,

I'm currently using a CommonJS/npm modules require implementation (npm-jvm) with Nashorn.

Roughly, the way it works (and I'm sure you're already familiar with this technique) is it takes the JavaScript module and wraps it in a Function object:

var body = readScriptAsText();
var args = ['exports', 'module', 'require', '__filename', '__dirname'];
var func = new Function(args, body);
func.apply(module, [module.exports, module, module.require, module.filename, dir]); // Execute it - this works fine

Now let's say the actual module (foomodule.js) we are loading contains this:

module.exports = function() {
    var num = 234;
    num.substr(1, 1); // Will throw TypeError here
}

I.e. it simply exports a function, which will throw a TypeError when it's executed.

When the exported function is executed it does indeed throw a TypeError:

var f = require("foomodule");

f(); // Throws TypeError

Unfortunately the fileName field of the TypeError is set to "<function>" not to "foomodule.js", which is unfriendly for the user.

This is understandable as the Function object which wraps the module doesn't know about "foomodule.js".

So.. my question is.. how do I tell the Function object that the "filename" it should use when exceptions are thrown from it is "foomodule.js"?

I have tried the following and none work:

var func = new Function(args, body);
func.name = "foomodule.js";
func.fileName = "foomodule.js";
func.displayName = "foomodule.js";

Any insights would be greatly appreciated.






Reply via email to