【问题标题】:How to read file content in Node.js and convert the data to JSON?如何在 Node.js 中读取文件内容并将数据转换为 JSON?
【发布时间】:2019-08-27 16:46:25
【问题描述】:

我正在尝试从 .json 文件发送数据作为 Node.js 的响应。我对它很陌生,我不知道如何处理缓冲区。

这就是我所做的:

const express = require('express');
const fs = require('fs');

const path = require('path');
const bodyParser = require('body-parser');

const app = express();

const port = 3000;

app.use(bodyParser.urlencoded({extended: false}));

app.use('/', (req, res, next) => {
    fs.readFile(path.join(__dirname, 'data', 'filename.json'), (err, content) => {
        res.send(JSON.stringify(content));
    })
});

app.listen(port, () => {
    console.log(`server is running on port: ${port}`)
});

我希望以 JSON 格式获取数据,但我得到的是一个缓冲区或只是数字。我想我没有正确理解一些概念。

【问题讨论】:

    标签: node.js readfile fs


    【解决方案1】:

    将缓冲区保存到变量中,然后使用toString() 方法和JSON.parse

    【讨论】:

    • 当我尝试在 .toString() 之后使用 JSON.parse() 时,我收到错误“SyntaxError: Unexpected token ] in JSON at position 0”。这是为什么?我检查了,该文件包含有效的 JSON。
    【解决方案2】:

    你想要做的是像这样指定编码:

    fs.readFile(path.join(__dirname, 'data', 'filename.json'), 'utf8', (err, content) => {
            res.setHeader('Content-Type', 'application/json');
            res.send(content); // content will be a string
        })
    

    否则根据documentation你会得到Buffer。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 2014-08-31
      相关资源
      最近更新 更多