njs: Segmentation fault when accessing variables outside in a module.

Hi, @xeioex

  1. segmentation fault when accessing variables outside in a module.

test.js

var a = 1
import foo from "foo.js"

foo.js

export default a
  1. I wonder if a module can access global variables outside? if not, is it possible to access global variables in modules?

  2. what’s the global only introduced in njs for?

Thanks.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 25 (25 by maintainers)

Commits related to this issue

Most upvoted comments

Hi @drsm,

Thanks for your valuable feedback.

Take a look at the second iteration.

Cyclic imports, relative paths, and export default sinking was fixed.

Hi @hongzhidao,

FYI, import binding are not automatically become globalThis properties (as it is in Node.js).

@xeioex

It looks like cyclic imports are not supported:

$ tail -v -n +1 a.js b.js c.js 
==> a.js <==
import b from 'b.js';
export default 1;

==> b.js <==
import a from 'a.js';
export default 1;

==> c.js <==
import a from 'a.js';
import b from 'b.js';
$ build/njs c.js 
Thrown:
ReferenceError: cannot access "./a.js" before initialization
    at ./b.js (./b.js:1)

BTW,

$ tail -v -n +1 a.js b.js c.js 
==> a.js <==
import b from './b.js';
export default 1;

==> b.js <==
import a from './a.js';
export default 1;

==> c.js <==
import a from './a.js';
import b from './b.js';
$ build/njs c.js 
Segmentation fault (core dumped)
$ tail -v -n +1 d.js b.js 
==> d.js <==
import b from 'b.js';

console.log(typeof b, b);

==> b.js <==
var o = {
    a: 1,
    b: 2,
};

export default o;

console.log(o); // will work if commented
$ build/njs d.js 
{a:1,b:2}
undefined undefined

Hi @hongzhidao, @drsm

Take a look at the patch. The patch adds the support of custom module loader callbacks.

...
this patch introduces HostResolveImportedModule support.
When vm->options.ops->module_loader is provided, a module lookup
and compilation is delegated to this callback.

The module_loader is called with vm, vm->external and module name as arguments.

The default loader is here.

@hongzhidao

Hi!

  1. looks like a nodejs related compatibility alias.
>> global === globalThis 
true

I wonder if a module can access global variables outside? if not, is it possible to access global variables in modules?

Yes. Anything defined in global scope will be a property of the globalThis object.

https://github.com/nginx/njs/issues/300#issuecomment-612049416

var a = 1
import foo from "foo.js"

In such case a is not a global, because module scopes are independent. And this

export default a

should not compile, because there is no a defined in module ‘foo.js’