Require module from string in Node.js
npx @tessl/cli install tessl/npm-require-from-string@2.0.00
# require-from-string
1
2
Load 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.
3
4
## Package Information
5
6
- **Package Name**: require-from-string
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install require-from-string`
10
11
## Core Imports
12
13
```javascript
14
const requireFromString = require("require-from-string");
15
```
16
17
## Basic Usage
18
19
```javascript
20
const requireFromString = require("require-from-string");
21
22
// Simple module execution
23
const result = requireFromString('module.exports = 1 + 2');
24
console.log(result); // 3
25
26
// Module with exports object
27
const utils = requireFromString(`
28
module.exports = {
29
add: (a, b) => a + b,
30
multiply: (a, b) => a * b
31
};
32
`);
33
console.log(utils.add(2, 3)); // 5
34
```
35
36
## Capabilities
37
38
### Module Execution
39
40
Load and execute JavaScript modules from string content with optional configuration.
41
42
```javascript { .api }
43
/**
44
* Dynamically require and execute JavaScript modules from string sources
45
* @param {string} code - JavaScript module code to execute (required)
46
* @param {string} [filename] - Optional filename for debugging/error reporting (default: '')
47
* @param {object} [opts] - Configuration options
48
* @param {Array} [opts.appendPaths] - Array of paths to append to module resolution paths
49
* @param {Array} [opts.prependPaths] - Array of paths to prepend to module resolution paths
50
* @returns {*} The module.exports value from the executed code string
51
* @throws {Error} Throws Error if code parameter is not a string
52
*/
53
function requireFromString(code, filename, opts);
54
```
55
56
**Parameter overloading**: When `filename` is an object, it's treated as the `opts` parameter and `filename` defaults to an empty string.
57
58
```javascript
59
// Standard usage
60
requireFromString(code, 'debug.js', { appendPaths: [...] });
61
62
// Filename omitted, options as second parameter
63
requireFromString(code, { appendPaths: [...] });
64
```
65
66
**Usage Examples:**
67
68
```javascript
69
const requireFromString = require("require-from-string");
70
71
// Basic execution
72
const simpleResult = requireFromString('module.exports = "Hello World"');
73
console.log(simpleResult); // "Hello World"
74
75
// With filename for better error messages
76
try {
77
requireFromString('throw new Error("Something went wrong")', 'test-module.js');
78
} catch (error) {
79
console.log(error.stack); // Stack trace includes 'test-module.js'
80
}
81
82
// With custom module resolution paths
83
const code = 'module.exports = require("custom-module");';
84
const result = requireFromString(code, 'dynamic.js', {
85
prependPaths: ['/path/to/custom/modules'],
86
appendPaths: ['/additional/module/path']
87
});
88
89
// Options-only usage (filename omitted)
90
const result2 = requireFromString(code, {
91
appendPaths: ['/extra/modules']
92
});
93
```
94
95
**Error Handling:**
96
97
The function throws an Error with the message "code must be a string, not [typeof code]" if the first parameter is not a string.
98
99
Runtime errors in the executed code are thrown with meaningful stack traces that include the provided filename for easier debugging.
100
101
**Internal Behavior:**
102
103
- Creates a new Module instance with the provided filename
104
- Sets up module resolution paths by combining prependPaths, standard node_modules paths, and appendPaths
105
- Compiles and executes the code string within the module context using Module._compile()
106
- Cleans up by removing the temporary module from the parent's children array to prevent memory leaks
107
- Returns the resulting module.exports value
108
109
## Types
110
111
```javascript { .api }
112
/**
113
* Options object for configuring module resolution paths
114
*/
115
interface RequireFromStringOptions {
116
/** Array of paths to append to module resolution paths */
117
appendPaths?: string[];
118
/** Array of paths to prepend to module resolution paths */
119
prependPaths?: string[];
120
}
121
```