使用 nodejs 在 JSON redis 中设置函数类型

Setting function type in JSON redis using nodejs

您好,我正在尝试使用 ioredis 在 redis 中存储 JSON。这个 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 来计算。

JSON 是一种将任意数据对象编码为字符串的方法,可以在稍后将其解析回其原始对象。因此,JSON 仅编码 "simple" 数据类型: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() 非常危险,因此已被弃用。