! /usr/bin/env node
const http = require(“http”);
const fs = require(“fs”);
const { join } = require(“path”);
const {networkInterfaces} = require(“os”); //获取本地ip
const {exec} = require(“child_process”); //自动打开浏览器
//获取命令行内容
let argv = process.argv.slice(2);
//设置默认端口号
let POST = “8080”;
let createReadFile = () => {
//创建服务
http.createServer((req, res) => {
//读取public/index.html
let html = fs.readFileSync(join(__dirname, “/public/index.html”)).toString();
//获取 Node.js 进程的当前工作目录,查找此目录下的文件
let dirPath = process.cwd();
//设置当前查找的路径,判断文件后缀不为ico
dirPath = req.url.split(“.”)[1] == “ico” ? dirPath : join(dirPath, req.url);
//判断是否是文件夹
if (fs.statSync(dirPath).isDirectory()) {
//读取当前目录下所有的文件文件夹
let dirArr = fs.readdirSync(dirPath);
//循环编写li字符串
let liHtml = dirArr.map(item=> {
return<li><br /> <a href=${join(req.url, item)}>${item}</a><br /> </li>
;
}).join(“”);
//在html中查找{{list}},替换为liHtml
html = html.replace(“{{list}}”, liHtml);
//结束响应,返回html字符串
res.end(html);
} else {
//结束响应,读取文件
res.end(fs.readFileSync(dirPath));
}
}).listen(POST, () => {
console.log(“起服务成功” + POST);
//获取本地ip
let listenPath = networkInterfaces()[“以太网”].find(item=>item.family === “IPv4”).address;
//启服务后自动打开浏览器
exec(start http://${listenPath}:${POST}
);
})
}
//判断是否传入了端口
if (argv.length > 0) {
//设置POST
POST = argv[1];
createReadFile()
} else {
createReadFile()
}