Skip to content

shahradelahi/node-eval

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

node-eval

CI NPM Version MIT License Install Size

neval is a zero-dependency, lightweight utility for securely evaluating code in a sandboxed environment in Node.js.


πŸ“¦ Installation

npm install neval

πŸ“– Usage

import { neval, nevalFile } from 'neval';

const result = neval('1 + 1');
console.log(result); // 2

const result2 = await nevalFile('./file.js');
console.log(result2); // Whatever file.js returns

const result3 = await neval(
  `
    async function main() {
        await sleep(1e3); // The "sleep" function will be injected through context
        return 1 + 1;
    }
    main();
`,
  {
    context: {
      sleep: async (ms: number) => {
        return new Promise((resolve) => setTimeout(resolve, ms));
      },
    },
  }
);
console.log(result3); // Result after 1 second is 2

const result4 = await neval(
  `
    fetch('https://example.com', { method: 'HEAD' })
      .then((resp) => resp.statusText);
`,
  {
    // By default, the "fetch" API is not available, you must add it to the context
    context: { fetch },
  }
);
console.log(result4); // OK

Importing neval/register will register the neval function on the global object and overrides the eval function.

import 'neval/register';

console.log(eval('1 + 1')); // 2

Why is it important to register it globally? The neval is sandboxed and much more secure than just using the eval function. Read more about eval.

Are you looking for more examples? Check out the unit tests.

πŸ“š Documentation

For all configuration options, please see the API docs.

API
function neval(code: any, options?: EvalOptions): any;
function nevalFile(path: string, options?: EvalOptions): Promise<any>;
function register(): void;

🀝 Contributing

Want to contribute? Awesome! To show your support is to star the project, or to raise issues on GitHub

Thanks again for your support, it is much appreciated! πŸ™

Relevant

License

MIT Β© Shahrad Elahi