Read file and eval it. Uses any-eval.
Like require, but asynchronous and doesn't use the module cache.
Important: internally file-eval will resolve passed relative paths with path.resolve(), not require.resolve().
In addition to JSON and CommonJS supports JSON5 data format.
$ npm install --save file-eval
const fileEval = require('file-eval');
fileEval('./path/to/file.js')
.then(console.log)
.catch(console.error);Type: String.
The filename or file descriptor.
The file-eval determinate format by extension. If filename ends with .js, its contents will be evaluating with vm.
If filename ends with .json extention, its contents will be parsing with JSON.parse. If filename ends with .json5 extention, its contents will be parsing with json5.
By default expected JS-expression or CommonJS module contents.
Type: Object, string.
Options or encoding.
Type: string.
Default: utf-8.
The file encoding.
Type: string.
Default: r.
The flag mode.
Type: Object.
The object to provide into execute method.
If context is specified, then module contents will be evaluating with vm.runInNewContext.
If context is not specified, then module contents will be evaluating with vm.runInThisContext.
With context you can provide some like-a-global variables into file-eval.
const fileEval = require('file-eval');
const secretKey = '^___^';
// The file has the contents "module.exports = secretKey;"
fileEval('./path/to/file.js', {
context: { secretKey }
});
// ➜ '^___^'Synchronous version of fileEval.
Method signature is same.
Supports CommonJS, JSON and JSON5 formats.
See examples with evaluating files with different formats.
Evaluates CommonJS files with .js extention.
const fileEval = require('file-eval');
// export data with `module.exports` or `exports`
fileEval('./path/to/file.js');Evaluates JSON files with .json extention.
const fileEval = require('file-eval');
fileEval('./path/to/file.json');Evaluates JSON5 files with .json5 extention.
JSON5 is not an official successor to JSON, and JSON5 content may not work with existing JSON parsers. For this reason, JSON5 files use a new
.json5extension.
const fileEval = require('file-eval');
fileEval('./path/to/file.json5');- node-eval — eval Node.js contents only (JS-expression, CommonJS modules and JSON).
- any-eval — eval any contents (JS-expression, CommonJS modules and JSON/JSON5).
- node-file-eval — read node.js file and eval it with node-eval.
MIT © Andrew Abramov