【问题标题】:Setting function type in JSON redis using nodejs使用nodejs在JSON redis中设置函数类型
【发布时间】:2019-06-08 10:49:21
【问题描述】:

您好,我正在尝试使用 ioredis 将 JSON 存储在 redis 中。这个 JSON 也包含一个函数。我的json的结构是这样的:

var object = {
  site1: {
    active: true,
    config1:{
      // Some config in JSON format
    },
    config2: {
      // Some other config in JSON format
    },
    determineConfig: function(condition){
      if(condition) {
        return 'config1';
      }
      return 'config2';
    }
  }
}

我正在使用 IOredis 将这个 json 存储在 redis 中:

redisClient.set(PLUGIN_CONFIG_REDIS_KEY, pluginData.pluginData, function (err, response) {
  if (!err) {
    redisClient.set("somekey", JSON.stringify(object), function (err, response) {
      if (!err) {
        res.json({message: response});
      }
    });
  }
});

当我这样做时,determineConfig 键会从 object 中截断,因为如果类型是函数,JSON.stringify 会删除它。有什么方法可以将这个函数存储在 redis 中,并在我从 redis 取回数据后执行。我不想将函数存储为字符串,然后使用evalnew Function 进行评估。

【问题讨论】:

    标签: node.js json redis ioredis


    【解决方案1】:

    JSON 是一种将任意数据对象编码为字符串的方法,这些字符串可以在以后解析回其原始对象。因此,JSON 仅编码“简单”数据类型:nulltruefalseNumberArrayObject

    JSON 不支持任何具有专用内部表示的数据类型,例如 Date、Stream 或 Buffer。

    要查看实际效果,请尝试

     typeof JSON.parse(JSON.stringify(new Date)) // => string
    

    由于它们的底层二进制表示无法编码为字符串,因此 JSON 不支持函数编码。

    JSON.stringify({ f: () => {} }) // => {}
    

    虽然您表示不希望这样做,但实现目标的唯一方法是将您的函数序列化为其源代码(由字符串表示),如下所示:

    const determineConfig = function(condition){
      if(condition) {
        return 'config1';
      }
      return 'config2';
    }
    
    {
      determineConfig: determineConfig.toString()
    }
    

    然后exec 或以其他方式在接收端重新实例化该函数。

    我建议不要这样做,因为exec() 非常危险,因此已被弃用。

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 1970-01-01
      • 2020-03-10
      • 2020-06-24
      • 2023-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多