如何将JavaScript字符串隐藏为node.js中的可执行代码

时间:2019-01-19 22:52:17

标签: javascript node.js ecmascript-6

我已将查询保存在数据库中。我可以字符串查询。

INSERT INTO alertsV SET Instance_ID = ${body.add.Instance_ID}

但是${body.add.Instance_ID}并没有替换为值。

预期结果应为INSERT INTO alertsV SET Instance_ID = 1234

我正在使用nodejs。请帮助我解决此问题。这是函数。

  saveFormData: async function (req, res) {
     let form_id = parseInt(req.body.form_id);
     let body = req.body.form_data;
     let saveQuery = await sails.orientDb.command('select actions.save as 
     saveQuery from form where form_id=' + form_id).one();

     saveQuery = saveQuery.saveQuery; // i can get string here 'INSERT INTO alertsV SET Instance_ID = ${body.add.Instance_ID}'
     let result = await sails.orientDb.command(saveQuery).one();
     return res.json(result);
  }

1 个答案:

答案 0 :(得分:0)

您可以将字符串包装在模板文字反引号中,然后将其传递到eval以运行字符串插值:

saveQuery = eval('`' + saveQuery.saveQuery + '`'); 

const a = 10;
const str = 'test ${a} test';

console.log(eval('`' + str + '`'));

/*
if it's required to wrap the interpolated value into a quotes, 
you can do that by wrapping the embedded expression, prior to interpolation:
*/
console.log(eval('`' + str.replace(/(\${.*})/, '\'$1\'') + '`'));