Require module from string in Node.js
npx @tessl/cli install tessl/npm-require-from-string@2.0.0Load and execute Node.js modules from string content instead of files. This utility creates a new Module instance, compiles the provided JavaScript code string within that context, and returns the resulting exports. It's particularly useful for dynamic code execution, template processing, testing frameworks, and build tools that need to manipulate JavaScript code at runtime.
npm install require-from-stringconst requireFromString = require("require-from-string");const requireFromString = require("require-from-string");
// Simple module execution
const result = requireFromString('module.exports = 1 + 2');
console.log(result); // 3
// Module with exports object
const utils = requireFromString(`
module.exports = {
add: (a, b) => a + b,
multiply: (a, b) => a * b
};
`);
console.log(utils.add(2, 3)); // 5Load and execute JavaScript modules from string content with optional configuration.
/**
* Dynamically require and execute JavaScript modules from string sources
* @param {string} code - JavaScript module code to execute (required)
* @param {string} [filename] - Optional filename for debugging/error reporting (default: '')
* @param {object} [opts] - Configuration options
* @param {Array} [opts.appendPaths] - Array of paths to append to module resolution paths
* @param {Array} [opts.prependPaths] - Array of paths to prepend to module resolution paths
* @returns {*} The module.exports value from the executed code string
* @throws {Error} Throws Error if code parameter is not a string
*/
function requireFromString(code, filename, opts);Parameter overloading: When filename is an object, it's treated as the opts parameter and filename defaults to an empty string.
// Standard usage
requireFromString(code, 'debug.js', { appendPaths: [...] });
// Filename omitted, options as second parameter
requireFromString(code, { appendPaths: [...] });Usage Examples:
const requireFromString = require("require-from-string");
// Basic execution
const simpleResult = requireFromString('module.exports = "Hello World"');
console.log(simpleResult); // "Hello World"
// With filename for better error messages
try {
requireFromString('throw new Error("Something went wrong")', 'test-module.js');
} catch (error) {
console.log(error.stack); // Stack trace includes 'test-module.js'
}
// With custom module resolution paths
const code = 'module.exports = require("custom-module");';
const result = requireFromString(code, 'dynamic.js', {
prependPaths: ['/path/to/custom/modules'],
appendPaths: ['/additional/module/path']
});
// Options-only usage (filename omitted)
const result2 = requireFromString(code, {
appendPaths: ['/extra/modules']
});Error Handling:
The function throws an Error with the message "code must be a string, not [typeof code]" if the first parameter is not a string.
Runtime errors in the executed code are thrown with meaningful stack traces that include the provided filename for easier debugging.
Internal Behavior:
/**
* Options object for configuring module resolution paths
*/
interface RequireFromStringOptions {
/** Array of paths to append to module resolution paths */
appendPaths?: string[];
/** Array of paths to prepend to module resolution paths */
prependPaths?: string[];
}