65

如果我将文件的内容作为字符串存储在内存中,而不将其写入磁盘,我将如何 require() 一个文件?这是一个例子:

// Load the file as a string
var strFileContents = fs.readFileSync( "./myUnalteredModule.js", 'utf8' );

// Do some stuff to the files contents
strFileContents[532] = '6';

// Load it as a node module (how would I do this?)
var loadedModule = require( doMagic(strFileContents) );
4

6 回答 6

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

console.log(requireFromString('module.exports = { test: 1}', ''));

查看 module.js 中的 _compile、_extensions 和_load

于 2013-07-11T05:09:55.293 回答
47

安德烈已经回答了这个问题,但我遇到了一个我必须解决的缺点,并且其他人可能会对此感兴趣。

我希望记忆字符串中的模块能够通过 加载其他模块require,但是上述解决方案破坏了模块路径(例如找不到针)。我试图找到一个优雅的解决方案来维护路径,通过使用一些现有的功能,但我最终还是硬连接了路径:

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

var codeString = 'var needle = require(\'needle\');\n'
  + '[...]\n'
  + 'exports.myFunc = myFunc;';

var virtMod = requireFromString(codeString);
console.log('Available public functions: '+Object.keys(virtMod));

之后,我能够从字符串化模块加载所有现有模块。任何意见或更好的解决方案高度赞赏!

于 2013-10-30T12:24:46.640 回答
11

require-from-string软件包完成了这项工作。

用法:

var requireFromString = require('require-from-string');

requireFromString('module.exports = 1');
//=> 1
于 2016-08-16T14:55:00.923 回答
4

在分析 和 等解决方案的源代码后piratesrequire-from-string我得出的结论是,简单的模拟fsModule方法在支持方面不会更差。并且在功能方面它会更好,因为它支持@babel/register,pirates和其他改变模块加载过程的模块。

你可以试试这个 npm 模块require-from-memory

import fs from 'fs'
import BuiltinModule from 'module'
const Module = module.constructor.length > 1 ? module.constructor : BuiltinModule

function requireFromString(code, filename) {
    if (!filename) {
        filename = ''
    }

    if (typeof filename !== 'string') {
        throw new Error(`filename must be a string: ${filename}`)
    }

    let buffer
    function getBuffer() {
        if (!buffer) {
            buffer = Buffer.from(code, 'utf8')
        }
        return buffer
    }

    const now = new Date()
    const nowMs = now.getTime()
    const size = Buffer.byteLength(code, 'utf8')
    const fileStat = {
        size,
        blksize    : 4096,
        blocks     : Math.ceil(size / 4096),
        atimeMs    : nowMs,
        mtimeMs    : nowMs,
        ctimeMs    : nowMs,
        birthtimeMs: nowMs,
        atime      : now,
        mtime      : now,
        ctime      : now,
        birthtime  : now
    }

    const resolveFilename = Module._resolveFilename
    const readFileSync = fs.readFileSync
    const statSync = fs.statSync
    try {
        Module._resolveFilename = () => {
            Module._resolveFilename = resolveFilename
            return filename
        }

        fs.readFileSync = (fname, options, ...other) => {
            if (fname === filename) {
                console.log(code)
                return typeof options === 'string'
                    ? code
                    : getBuffer()
            }
            console.log(code)
            return readFileSync.apply(fs, [fname, options, ...other])
        }

        fs.statSync = (fname, ...other) => {
            if (fname === filename) {
                return fileStat
            }
            return statSync.apply(fs, [fname, ...other])
        }

        return require(filename)
    } finally {
        Module._resolveFilename = resolveFilename
        fs.readFileSync = readFileSync
        fs.statSync = statSync
    }
}
于 2019-03-08T10:00:12.297 回答
2

基于 Andrey Sidorov 和 Dominic 解决方案,我对无法要求字符串化模块的事实感到难过,然后我建议使用此版本 *.

代码:

void function() {
    'use strict';

    const EXTENSIONS = ['.js', '.json', '.node'];

    var Module,
        path,
        cache,
        resolveFilename,
        demethodize,
        hasOwnProperty,
        dirname,
        parse,
        resolve,
        stringify,
        virtual;

    Module = require('module');
    path = require('path');

    cache = Module._cache;
    resolveFilename = Module._resolveFilename;

    dirname = path.dirname;
    parse = path.parse;
    resolve = path.resolve;
    demethodize = Function.bind.bind(Function.call);
    hasOwnProperty = demethodize(Object.prototype.hasOwnProperty);

    Module._resolveFilename = function(request, parent) {
        var filename;

        // Pre-resolution
        filename = resolve(parse(parent.filename).dir, request);

        // Adding extension, if needed
        if (EXTENSIONS.indexOf(parse(filename).ext) === -1) {
            filename += '.js';
        }

        // If the module exists or is virtual, return the filename
        if (virtual || hasOwnProperty(cache, filename)) {
            return filename;
        }

        // Preserving the native behavior
        return resolveFilename.apply(Module, arguments);
    };

    Module._register = function(request, parent, src) {
        var filename,
            module;

        // Enabling virtual resolution
        virtual = true;

        filename = Module._resolveFilename(request, parent);

        // Disabling virtual resolution
        virtual = false;

        // Conflicts management
        if (hasOwnProperty(cache, filename)) {
            error = new Error('Existing module "' + request + '"');
            error.code = 'MODULE_EXISTS';

            throw error;
        }

        // Module loading
        cache[filename] = module = new Module(filename, parent);
        module.filename = filename;
        module.paths = Module._nodeModulePaths(dirname(filename));
        module._compile(stringify(src), filename);
        module.loaded = true;

        return module;
    };

    stringify = function(src) {
        // If src is a function, turning to IIFE src
        return typeof src === 'function'
            ? 'void ' + src.toString() + '();'
            : src;
    };
}();

void function() {
    var Module,
        parentModule,
        child;

    Module = require('module');

    // Creating a parent module from string
    parentModule = Module._register('parent', process.mainModule, `
        module.exports = {
            name: module.filename,
            getChild: function() {
                return require('child');
            }
        };
    `);

    // Creating a child module from function
    Module._register('child', parentModule, function() {
        module.exports = {
            name: module.filename,
            getParent: function() {
                return module.parent.exports;
            }
        };
    });

    child = require('child');

    console.log(child === child.getParent().getChild());
}();

用法:

void function() {
    var Module,
        parentModule,
        child;

    Module = require('module');

    // Creating a parent module from string
    parentModule = Module._register('parent', process.mainModule, `
        module.exports = {
            name: module.filename,
            getChild: function() {
                return require('child');
            }
        };
    `);

    // Creating a child module from function
    Module._register('child', parentModule, function() {
        module.exports = {
            name: module.filename,
            getParent: function() {
                return module.parent.exports;
            }
        };
    });

    child = require('child');

    console.log(child === child.getParent().getChild());
}();

* 如您所见,它包含一个函数格式化程序,它提供了一种从函数创建一些模块的方法。

于 2015-02-22T13:01:10.050 回答
-3

我认为解决这个问题的更好方法是有一个你可以在之后设置的参数......

比如里面的文件:myUnalteredModule.js

exports.setChanges = function( args )...

然后你可以这样做:

 var loadedModule = require( 'myUnalteredModule' );
loadedModule
于 2013-07-10T23:27:56.840 回答