如何读取Node.js中的文件内容并将数据转换为JSON?

How to read file content in Node.js and convert the data to JSON?

我正在尝试从 .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 格式的数据,但我得到的是一个缓冲区或只是数字。我想我没有正确理解一些概念。

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

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。

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