蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行基于临时 users.json 的本地 RESTful CRUD 服务实测

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-restful-api.mjs
explore-restful-api.mjs195 行
import http from 'node:http';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';

const INITIAL_USERS = {
  user1: { name: 'mahesh', password: 'password1', profession: 'teacher', id: 1 },
  user2: { name: 'suresh', password: 'password2', profession: 'librarian', id: 2 },
  user3: { name: 'ramesh', password: 'password3', profession: 'clerk', id: 3 },
};

async function readJsonBody(req) {
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  if (chunks.length === 0) return {};
  return JSON.parse(Buffer.concat(chunks).toString('utf8'));
}

async function main() {
  const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'mbsky-rest-'));
  const dataFile = path.join(tmpDir, 'users.json');
  await fs.writeFile(dataFile, JSON.stringify(INITIAL_USERS, null, 2), 'utf8');

  const sendJson = (res, status, payload) => {
    res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
    res.end(JSON.stringify(payload));
  };

  const server = http.createServer(async (req, res) => {
    const pathname = new URL(req.url || '/', 'http://127.0.0.1').pathname;
    const raw = await fs.readFile(dataFile, 'utf8');
    const users = JSON.parse(raw);

    if (req.method === 'GET' && pathname === '/listUsers') {
      return sendJson(res, 200, users);
    }
    if (req.method === 'POST' && pathname === '/addUser') {
      const payload = await readJsonBody(req);
      Object.assign(users, payload);
      await fs.writeFile(dataFile, JSON.stringify(users, null, 2), 'utf8');
      return sendJson(res, 201, users);
    }
    if (req.method === 'DELETE' && pathname === '/deleteUser') {
      const payload = await readJsonBody(req);
      const key = `user${payload.id}`;
      if (!users[key]) return sendJson(res, 404, { error: 'User not found' });
      delete users[key];
      await fs.writeFile(dataFile, JSON.stringify(users, null, 2), 'utf8');
      return sendJson(res, 200, users);
    }

    const idMatch = pathname.match(/^\/(\d+)$/);
    if (idMatch && req.method === 'GET') {
      const user = users[`user${idMatch[1]}`];
      if (!user) return sendJson(res, 404, { error: 'User not found' });
      return sendJson(res, 200, user);
    }
    if (idMatch && req.method === 'PUT') {
      const key = `user${idMatch[1]}`;
      if (!users[key]) return sendJson(res, 404, { error: 'User not found' });
      const patch = await readJsonBody(req);
      users[key] = { ...users[key], ...patch, id: Number(idMatch[1]) };
      await fs.writeFile(dataFile, JSON.stringify(users, null, 2), 'utf8');
      return sendJson(res, 200, users[key]);
    }
    return sendJson(res, 404, { error: 'Route not found' });
  });

  const cases = [];
  try {
    await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
    const { port } = server.address();
    const base = `http://127.0.0.1:${port}`;

    // Case 1: get_list_users
    const listRes = await fetch(`${base}/listUsers`);
    const listData = await listRes.json();
    const actual1 = {
      status: listRes.status,
      keys: Object.keys(listData),
      count: Object.keys(listData).length,
      user2Name: listData.user2.name,
    };
    const expected1 = {
      status: 200,
      keys: ['user1', 'user2', 'user3'],
      count: 3,
      user2Name: 'suresh',
    };
    cases.push({
      name: 'get_list_users',
      passed: JSON.stringify(actual1) === JSON.stringify(expected1),
      expected: expected1,
      actual: actual1,
    });

    // Case 2: get_user_by_id
    const u2Res = await fetch(`${base}/2`);
    const u2Data = await u2Res.json();
    const missRes = await fetch(`${base}/99`);
    const missData = await missRes.json();
    const actual2 = {
      foundStatus: u2Res.status,
      user2: u2Data,
      missStatus: missRes.status,
      missError: missData.error,
    };
    const expected2 = {
      foundStatus: 200,
      user2: { name: 'suresh', password: 'password2', profession: 'librarian', id: 2 },
      missStatus: 404,
      missError: 'User not found',
    };
    cases.push({
      name: 'get_user_by_id',
      passed: JSON.stringify(actual2) === JSON.stringify(expected2),
      expected: expected2,
      actual: actual2,
    });

    // Case 3: post_add_user
    const addRes = await fetch(`${base}/addUser`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        user4: { name: 'mohit', password: 'password4', profession: 'teacher', id: 4 },
      }),
    });
    const addData = await addRes.json();
    const u4Data = await (await fetch(`${base}/4`)).json();
    const actual3 = {
      status: addRes.status,
      keys: Object.keys(addData),
      user4Name: u4Data.name,
      user4Id: u4Data.id,
    };
    const expected3 = {
      status: 201,
      keys: ['user1', 'user2', 'user3', 'user4'],
      user4Name: 'mohit',
      user4Id: 4,
    };
    cases.push({
      name: 'post_add_user',
      passed: JSON.stringify(actual3) === JSON.stringify(expected3),
      expected: expected3,
      actual: actual3,
    });

    // Case 4: delete_user_and_put_update
    const putRes = await fetch(`${base}/3`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ profession: 'senior-clerk' }),
    });
    const putData = await putRes.json();
    const delRes = await fetch(`${base}/deleteUser`, {
      method: 'DELETE',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: 2 }),
    });
    const delData = await delRes.json();
    const actual4 = {
      putStatus: putRes.status,
      updatedProfession: putData.profession,
      deleteStatus: delRes.status,
      remainingKeys: Object.keys(delData),
      user2Exists: 'user2' in delData,
    };
    const expected4 = {
      putStatus: 200,
      updatedProfession: 'senior-clerk',
      deleteStatus: 200,
      remainingKeys: ['user1', 'user3', 'user4'],
      user2Exists: false,
    };
    cases.push({
      name: 'delete_user_and_put_update',
      passed: JSON.stringify(actual4) === JSON.stringify(expected4),
      expected: expected4,
      actual: actual4,
    });
  } finally {
    await new Promise((resolve) => server.close(resolve));
    await fs.rm(tmpDir, { recursive: true, force: true });
  }

  console.log(JSON.stringify({ version: process.version, cases }));
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Node.js v24.22.3 本地运行环境。

入口文件:projects/nodejs-restful-api-lab/explore-restful-api.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-restful-api.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Node.js

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip

下载课程关联工程包:Node.js

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1070.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习