最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Alternative to eval() in node script - Stack Overflow

programmeradmin0浏览0评论

I am working on a script that runs during our build process in Jenkins right before npm install. My issue is that I need to download a JavaScript file from an external resource and read a variable from it.

unzipper.on('extract', () => { 
  const content = fs.readFileSync(`${outputDir}/js/en.js`, 'utf8');
  eval(content); // Less smellier alternative?

  if (obj) {
    const str = JSON.stringify(obj);
    fs.writeFileSync(`${outputDir}/public/data.json`, str);
  } else {
    throw 'Variable `obj` not found';
  }
});

I know that "eval is evil", but any suggested alternatives I've found online don't seem to work. I have tried different variations of new Function(obj)(), but Node seems to exit the script after (the if-case never runs).

Ideas?

I am working on a script that runs during our build process in Jenkins right before npm install. My issue is that I need to download a JavaScript file from an external resource and read a variable from it.

unzipper.on('extract', () => { 
  const content = fs.readFileSync(`${outputDir}/js/en.js`, 'utf8');
  eval(content); // Less smellier alternative?

  if (obj) {
    const str = JSON.stringify(obj);
    fs.writeFileSync(`${outputDir}/public/data.json`, str);
  } else {
    throw 'Variable `obj` not found';
  }
});

I know that "eval is evil", but any suggested alternatives I've found online don't seem to work. I have tried different variations of new Function(obj)(), but Node seems to exit the script after (the if-case never runs).

Ideas?

Share Improve this question asked Nov 8, 2019 at 15:23 ChrisChris 59.6k20 gold badges120 silver badges142 bronze badges 19
  • 1 what is the variable? Is it just hard coded or is it like a method? – epascarello Commented Nov 8, 2019 at 15:26
  • @epascarello, it's a fairly big js object. – Chris Commented Nov 8, 2019 at 15:26
  • 2 If you know the provenance of the script and trust it (with a high level of trust), it's fine to use eval. It's blindly using it for arbitrary script that's evil. – Heretic Monkey Commented Nov 8, 2019 at 15:26
  • 1 It's only evil if used inappropriately, especially client side or in places where the javascript input can not be guaranteed safe. Doing new Function is literally the same as eval apart from the need to call the new function declaration to run the evaluated code. Eval is typically also avoided because its slow, but there's no other way to evaluate JS - an alternative would be to write some kind of Regex parser yourself but that might be too plicated for the task - especially if you're ok with the above.. – Adrian Commented Nov 8, 2019 at 15:27
  • 1 @Chris: you do have read access, as it's obvious from your code. What I meant is literally: content += '; module.exports=obl'; writeFile(temp, content);obj=require(temp) – georg Commented Nov 8, 2019 at 15:43
 |  Show 14 more ments

2 Answers 2

Reset to default 5

Since node.js provides the API to talk to the V8 runner directly, it might be a good idea to use it. Basically, it's the API used by node's require under the hood.

Assuming the js file in question contains the variable obj we're interested in, we do the following:

  • read the code from the file
  • append ; obj to the code to make sure it's the last expression it evaluates
  • pass the code to V8 for evaluation
  • grab the return value (which is our obj):
    const fs = require('fs'),
        vm = require('vm');

    const code = fs.readFileSync('path-to-js-file', 'utf8');
    const obj = vm.runInNewContext(code + ';obj');

This answer is heavily based on @georg's ments, but since it helped me I'll provide it as an alternative answer.

Explanation in the ments.

let content = fs.readFileSync(`${outputDir}/js/en.js`, 'utf8');
content += '; module.exports=obj'; // Export "obj" variable

fs.writeFileSync(`${outputDir}/temp`, content); // Create a temporary file
const obj = require(`${outputDir}/temp`); // Import the variable from the temporary file
fs.unlinkSync(`${outputDir}/temp`); // Remove the temporary file
发布评论

评论列表(0)

  1. 暂无评论