const fs = require("fs"); const http = require("http"); const WebSocket = require("ws");…
- User
const fs = require("fs"); const http = require("http"); const WebSocket = require("ws"); const path = require("path"); const url = require("url"); const uuid = require("uuid");
// 静态文件服务的目录 const staticBasePath = "./uploads"; // 用于存储从 HTTP 请求中获得的 host 名称 let hostName;
const server = http.createServer((req, res) => { // 存储请求的 host 名称 hostName = req.headers.host;
codeconst parsedUrl = url.parse(req.url); const sanitizePath = path.normalize(parsedUrl.pathname).replace(/^(…[/\])+/, ‘’); let pathname = path.join(staticBasePath, sanitizePath); fs.exists(pathname, function (exist) { if (!exist) { // 不存在的 url 将返回 404 res.statusCode = 404; res.end(文件 ${ pathname } 未找到!); return; } // 根据文件存在进行读取并返回 fs.readFile(pathname, function (err, data) { if (err) { res.statusCode = 500; res.end(`无法读取文件: ${ err }.`); } else { const ext = path.parse(pathname).ext; res.setHeader('Content - Type', 'application / octet - stream'); res.end(data); } }); });});
const wss = new WebSocket.Server({ server });
wss.on("connection", ws => { ws.on("message", message => { const data = JSON.parse(message);
code - Assistant
There are several errors and issues with the provided code snippet. I'll go through them and give you the corrected line or explanation for each:
-
The replace function on
sanitizePathline contains non-standard quotation marks. It should use regular single or double quotes, not ‘’.
-