【问题标题】:How can you stream a JSON file in Node.js and interpret it as JSON?如何在 Node.js 中流式传输 JSON 文件并将其解释为 JSON?
【发布时间】:2013-05-16 09:44:12
【问题描述】:

我有一个 JSON 文件,我想在 Node.js 脚本中使用它。我想传递 json,然后传递脚本来解析它。我尝试使用fs.readFileSync(filename),但这会返回一个缓冲区。如何将其转换回 JSON 以便我可以解析它?

【问题讨论】:

  • require('filename.json')?

标签: json node.js buffer fs


【解决方案1】:

如果从缓冲区读取,可以使用JSON.parse() 进行转换。

> var fs = require('fs');
undefined
> a=fs.readFileSync('a.json');
<Buffer 7b 0d 0a 20 20 20 20 22 67 6c 6f 73 73 61 72 79 22 ...>
> JSON.parse(a);
{ glossary:
   { title: 'example glossary',
     GlossDiv: { title: 'S', GlossList: [Object] } } }

文件必须是有效的 JSON。

你也可以require直接加载JSON。

> var a=require('a.json');
undefined
> a
{ glossary:
   { title: 'example glossary',
     GlossDiv: { title: 'S', GlossList: [Object] } } }

默认情况下需要检查当前目录内的node_modules 文件夹而不是当前文件夹。所以你应该给出路径。

【讨论】:

    猜你喜欢
    • 2012-09-09
    • 2019-01-10
    • 2020-09-14
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多