MST

星途 面试题库

面试题:Node.js 文件系统与HTTP集成之动态内容处理

假设你有一个包含用户数据的JSON文件,如何通过Node.js的HTTP服务器实现根据不同的URL参数,从文件中读取特定用户的数据并返回给客户端。请阐述整体思路并给出核心代码。
13.2万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试

整体思路

  1. 使用Node.js内置的fs模块读取JSON文件,获取用户数据。
  2. 使用http模块创建HTTP服务器。
  3. 解析URL中的参数,根据参数在用户数据中查找特定用户的数据。
  4. 将找到的用户数据作为响应返回给客户端。

核心代码

const http = require('http');
const fs = require('fs');
const url = require('url');

// 读取JSON文件
const userData = JSON.parse(fs.readFileSync('users.json', 'utf8'));

const server = http.createServer((req, res) => {
    const queryObject = url.parse(req.url, true).query;
    const userId = queryObject.id;

    // 根据id查找用户
    const user = userData.find(u => u.id === userId);

    if (user) {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(user));
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('User not found');
    }
});

const port = 3000;
server.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

假设users.json文件格式如下:

[
    { "id": "1", "name": "Alice" },
    { "id": "2", "name": "Bob" }
]

通过访问http://localhost:3000?id=1即可获取id为1的用户数据。