1

I have this code which creates a Node.js module from memory:

function requireFromString(src, filename) {
  var Module = module.constructor;
  var m = new Module(filename);
  m._compile(src, filename);
  return m;
}

console.log(
  requireFromString(
    'module.exports = { test: 1}',
    '/some/file/path.js'
  )
);

when I run it I get this output:

Module {
  id: '/some/file/path.js',
  exports: { test: 1 },
  parent: undefined,
  filename: null,     // <<< humma?
  loaded: false,
  children: [] }

does anyone know why filename is null? seems funny that id is the filename, and filename is null. I am on Node.js version 10.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 1
    what are you trying to archive? you are not suppose to call a `_` prefixed method. Also the `_compile` method was changed since node v6 https://github.com/nodejs/node/issues/11461#issuecomment-280905949 – William Chong Nov 22 '18 at 09:27
  • nah my code looks fine according to this: https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/loader.js#L678 – Alexander Mills Nov 22 '18 at 09:34
  • I was just asking the question b/c I am curious, but ultimately I am just trying to load a module from memory instead of from disk. I want to know what filename to use when loading from memory. – Alexander Mills Nov 22 '18 at 09:35
  • https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/loader.js#L616 well `filename` get assigned on `.load()`, but if you directly call `_compiled()` you would have skipped that step – William Chong Nov 22 '18 at 09:44
  • ahh i see, will take a look at that tomorrow thanks – Alexander Mills Nov 22 '18 at 10:33

1 Answers1

1

If you look at the Module constructor, it actually does this.filename = null

The filename is later set in Module.prototype._load which resolves the filename and calls module.load to set the internal property this.filename.

In your case you are calling _compile directly without loading the file, so the filename property remains null.

This is just an overview, the internal logic of require is quite complex with a lot of caching and native function calls, so I don't think you should try to use the filename property in your code.

If you need to somehow use the file name, I would create a new property in your code, let's say myfilename, making sure it doesn't interfere with node's internal logic.

mihai
  • 37,072
  • 9
  • 60
  • 86