nodejs服务器访问本地html页面
index.js
js
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
// 服务器配置
const PORT = 3000;
const HOSTNAME = 'localhost';
// 静态文件根路径(相对于当前脚本所在目录)
// - editorInstance
// - html
// - index.html // 目标页面
// - index.js // 服务器入口文件
const pathStr = '/editorInstance/html/index.html';
// 终端运行 node index.js
// 浏览器访问 http://localhost:3000/mytest/editorInstance/html/index.html
// MIME类型映射
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.wasm': 'application/wasm'
};
// 创建HTTP服务器
const server = http.createServer((req, res) => {
console.log(`${req.method} ${req.url}`);
// 解析请求URL
const parsedUrl = url.parse(req.url);
let pathname = parsedUrl.pathname;
// 处理根路径请求
if (pathname === '/') {
pathname = pathStr;
}
// 构建文件路径
const filePath = path.join(__dirname, pathname);
// 获取文件扩展名
const extname = String(path.extname(filePath)).toLowerCase();
// 设置默认MIME类型
const contentType = mimeTypes[extname] || 'application/octet-stream';
// 读取并返回文件
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
// 文件未找到
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1><p>The file was not found on this server.</p>', 'utf-8');
} else {
// 服务器错误
res.writeHead(500);
res.end(`Server Error: ${error.code}`, 'utf-8');
}
} else {
// 文件存在,返回文件内容
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
// 启动服务器
server.listen(PORT, HOSTNAME, () => {
console.log(`Server running at http://${HOSTNAME}:${PORT}/`);
console.log(`HTML编辑器页面: http://${HOSTNAME}:${PORT}${pathStr}`);
});这里再放一个对应的js模板的配置
json
{
// Place your snippets for javascript here. Each snippet is defined under a snippet name and has a prefix, body and
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the
// same ids are connected.
// Example:
// "Print to console": {
// "prefix": "log",
// "body": [
// "console.log('$1');",
// "$2"
// ],
// "description": "Log output to console"
// }
"Static File Server": {
"prefix": "pfile",
"body": [
"const http = require('http');",
"const fs = require('fs');",
"const path = require('path');",
"const url = require('url');",
"",
"// 服务器配置",
"const PORT = 3000;",
"const HOSTNAME = 'localhost';",
"const pathStr = '/editorInstance/html/index.html';",
"",
"// MIME类型映射",
"const mimeTypes = {",
"\t'.html': 'text/html',",
"\t'.js': 'text/javascript',",
"\t'.css': 'text/css',",
"\t'.json': 'application/json',",
"\t'.png': 'image/png',",
"\t'.jpg': 'image/jpg',",
"\t'.gif': 'image/gif',",
"\t'.svg': 'image/svg+xml',",
"\t'.wav': 'audio/wav',",
"\t'.mp4': 'video/mp4',",
"\t'.woff': 'application/font-woff',",
"\t'.ttf': 'application/font-ttf',",
"\t'.eot': 'application/vnd.ms-fontobject',",
"\t'.otf': 'application/font-otf',",
"\t'.wasm': 'application/wasm'",
"};",
"",
"const server = http.createServer((req, res) => {",
"\tconsole.log(req.method + ' ' + req.url);",
"\tconst parsedUrl = url.parse(req.url);",
"\tlet pathname = parsedUrl.pathname;",
"\tif (pathname === '/') pathname = pathStr;",
"",
"\tconst filePath = path.join(__dirname, pathname);",
"\tconst extname = String(path.extname(filePath)).toLowerCase();",
"\tconst contentType = mimeTypes[extname] || 'application/octet-stream';",
"",
"\tfs.readFile(filePath, (error, content) => {",
"\t\tif (error) {",
"\t\t\tif (error.code === 'ENOENT') {",
"\t\t\t\tres.writeHead(404, { 'Content-Type': 'text/html' });",
"\t\t\t\tres.end('<h1>404 Not Found</h1><p>The file was not found on this server.</p>', 'utf-8');",
"\t\t\t} else {",
"\t\t\t\tres.writeHead(500);",
"\t\t\t\tres.end('Server Error: ' + error.code, 'utf-8');",
"\t\t\t}",
"\t\t} else {",
"\t\t\tres.writeHead(200, { 'Content-Type': contentType });",
"\t\t\tres.end(content, 'utf-8');",
"\t\t}",
"\t});",
"});",
"",
"server.listen(PORT, HOSTNAME, () => {",
"\tconsole.log('Server running at http://' + HOSTNAME + ':' + PORT + '/');",
"\tconsole.log('HTML编辑器页面: http://' + HOSTNAME + ':' + PORT + pathStr);",
"});"
],
"description": "Launch a static-file server for the HTML editor"
}
}