基于node快速创建一个文件下载的mock服务

133 阅读1分钟

创建文件,编写内容

FileDownloadMockAPI.js

var fs = require("fs");
var http = require("http");
var os = require("os");
var url = require("url");

// post参数解析详见: https://blog.csdn.net/weixin_43972992/article/details/104874965

var ipAddress = getIpAddress();
/**
 * 获取当前机器的ip地址
 */
function getIpAddress() {
  var ifaces = os.networkInterfaces();

  for (var dev in ifaces) {
    let iface = ifaces[dev];

    for (let i = 0; i < iface.length; i++) {
      let { family, address, internal } = iface[i];

      if (family === "IPv4" && address !== "127.0.0.1" && !internal) {
        return address;
      }
    }
  }
}

var server = http.createServer();

server.on("request", function (request, response) {
  // 获取请求URL
  const { query, pathname } = url.parse(request.url, true);
  const method = request.method;
  if ("/favicon.ico" === pathname && method === "GET") {
    return;
  }
  console.log(query);
  console.log(pathname);
  if (pathname === "/") {
    response.writeHead(200, { "Content-Type": "text/plain; charset=UTF-8" });
    response.end("Hello World! 这是简单的web服务器测试。\n");
  } else if (pathname.indexOf("/download/") >= 0) {
    // 如果是下载文件的URL,则判断进行处理
    // 请求路径示例: http://localhost:8080/download/hello.xls
    // 提取文件名hello.xls
    var name = pathname.substring(pathname.lastIndexOf("/"));
    // 创建可读流,读取当前项目目录下的hello.xls文件
    const filePath = __dirname + "/" + name;
    const stats = fs.statSync(filePath);
    var rs = fs.createReadStream(filePath);
    // 设置响应请求头,200表示成功的状态码,headers表示设置的请求头
    response.writeHead(200, {
      // 'Content-Type': 'application/force-download',
      "Content-Type": "application/octet-stream",
      "Content-Disposition": "attachment;filename=" + name,
      "Content-Length": stats.size,
    });
    // 将可读流传给响应对象response
    rs.pipe(response);
  } else if (pathname.indexOf("/exp/") >= 0 || pathname.indexOf("/exp") >= 0) {
    response.writeHead(500, {
      "Content-Type": "application/json; charset=UTF-8",
    });
    response.end(JSON.stringify({ msg: "错误提示信息" }));
  } else if(pathname.indexOf("/redirect/") >= 0 || pathname.indexOf("/redirect")>=0){
    response.writeHead(301, { Location: "http://w3docs.com" });
    response.end();
  }else {
    response.writeHead(200, {
      "Content-Type": "application/json; charset=UTF-8",
    });
    response.end(JSON.stringify({ name: "test" }));
  }
});

const args = process.argv.slice(2);
const port = args ? parseInt(args) : 8888;

server.listen(port, "0.0.0.0", function () {
  console.log(
    `服务器启动成功,可以通过 http://${
      ipAddress ?? "127.0.0.1"
    }:${port} 来进行访问`
  );
});

启动该web服务

不指定端口则默认端口使用 8888

node FileDownloadMockAPI.js

指定端口

node FileDownloadMockAPI.js 8080

访问服务

首页

http://localhost:8888

异常接口

http://localhost:8888/exp

文件下载接口 P.S. abc.xls请自行创建,并放在FileDownloadMockAPI.js文件的同级目录下

http://localhost:8888/download/abc.xls

redirect接口

http://localhost:8888/redirect