index.js 866 B

12345678910111213141516171819202122232425262728293031323334
  1. 'use strict';
  2. var Module = require('module');
  3. var path = require('path');
  4. module.exports = function requireFromString(code, filename, opts) {
  5. if (typeof filename === 'object') {
  6. opts = filename;
  7. filename = undefined;
  8. }
  9. opts = opts || {};
  10. filename = filename || '';
  11. opts.appendPaths = opts.appendPaths || [];
  12. opts.prependPaths = opts.prependPaths || [];
  13. if (typeof code !== 'string') {
  14. throw new Error('code must be a string, not ' + typeof code);
  15. }
  16. var paths = Module._nodeModulePaths(path.dirname(filename));
  17. var parent = module.parent;
  18. var m = new Module(filename, parent);
  19. m.filename = filename;
  20. m.paths = [].concat(opts.prependPaths).concat(paths).concat(opts.appendPaths);
  21. m._compile(code, filename);
  22. var exports = m.exports;
  23. parent && parent.children && parent.children.splice(parent.children.indexOf(m), 1);
  24. return exports;
  25. };