代码片段
1 十进制转化为十六进制计算器
console.log("-------------------");
console.log("10进制转化为16进制");
console.log("-------------------");
console.log("请输入一个数字: \r\n");
const numRegExp = /^[0-9]*$/;
function warpper(hex) {
if (!hex) return 0;
if (hex.length % 2 == 1) return `0${hex}`.toUpperCase();
return hex.toUpperCase();
}
process.stdin.on("data", (buffer) => {
const data = buffer.toString();
if (!numRegExp.test(data.trim())) {
console.error("无效输入, 请输入一个数字");
} else {
const hex = Number(data.trim()).toString(16);
console.log("16进制结果为: %s \r\n", warpper(hex));
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2 图片访问服务
const http = require("http");
const fs = require("fs");
const IMAGE_DIR = "./images";
const PORT = 2000;
if (!fs.existsSync(IMAGE_DIR)) fs.mkdirSync(IMAGE_DIR);
http
.createServer((req, res) => {
const ip = req.socket.remoteAddress;
const port = req.socket.remotePort;
const path = req.url;
console.log(
`[${new Date().toLocaleString()}] request from [${ip}:${port}${path}]`
);
if (path.startsWith("/image/")) {
const imageName = path.split("/").filter((v) => !!v)[1];
fs.readFile(`./images/${imageName}`, "binary", (err, file) => {
if (err) {
res.writeHead(404);
res.end("Image not found");
} else {
res.writeHead(200, { "Content-Type": "image/png" });
res.write(file, "binary");
res.end();
}
});
} else {
res.end(JSON.stringify({ code: 0, message: "success", data: null }));
}
})
.listen(PORT);
console.log(`[${new Date().toLocaleString()}] Server running at port ${PORT}`);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37