面试题答案
一键面试整体思路
- 使用Node.js内置的
fs
模块读取JSON文件,获取用户数据。 - 使用
http
模块创建HTTP服务器。 - 解析URL中的参数,根据参数在用户数据中查找特定用户的数据。
- 将找到的用户数据作为响应返回给客户端。
核心代码
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的用户数据。