neval
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

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

Package Sidebar

Install

npm i neval

Weekly Downloads

118

Version

0.1.0

License

MIT

Unpacked Size

22.8 kB

Total Files

10

Last publish

Collaborators

  • shahradelahi