如何将巨大的 json 文件(550MB)包含到 Node.js 脚本中?
我尝试过:
var json = require('./huge-data-set.json')
该脚本是使用增加的 --max-old-space-size 参数执行的
node --max-old-space-size=4096 diff.js
它失败了:
buffer.js:500
throw new Error('"toString()" failed');
^
Error: "toString()" failed
at Buffer.toString (buffer.js:500:11)
at Object.fs.readFileSync (fs.js:552:33)
at Object.Module._extensions..json (module.js:556:20)
最佳答案
Node 背后是实现 JS 实现的 v8 引擎。 V8 是用 C++ 编写的,因此它使用类型将其字符保存在字符串中(此处谨慎使用讽刺)。
按照 ECMA 的规定,JavaScript 将每个字符存储在两个字节上(utf16 编码)。
The String type is the set of all ordered sequences of zero or more 16-bit unsigned integer values (“elements”) up to a maximum length of 2^53-1 elements
所以您遇到的不是内存不足限制,而是操作失败,因为字符串大于字符串类型的字节大小。
如果您尝试在 javascript 中编写 json 对象,而不是从 fs 读取它(通过要求它),那么您将遇到内存不足异常,因为设置了限制以防止此类情况发生。
关于javascript - 将巨大的 json 包含到 node.js 脚本中的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38883734/