通常,您最好为节点使用网络服务器,例如 Express.js。但出于教育目的,我会尝试以下方法。
在您的server.js 文件旁边创建一个名为public 的文件夹并添加以下三个文件:
- 404.html
- index.html
- otherpage.html
404.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>404</title>
</head>
<body>
<p>Oops! Page not found...</p>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index page</title>
</head>
<body>
<p>This is the index page</p>
</body>
</html>
otherpage.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>The other page</p>
</body>
</html>
最后是节点网络服务器 server.js:
const util = require('util');
const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');
// Promisify some functions so async/await syntax can be used
const fsReaddir = util.promisify(fs.readdir);
const fsReadFile = util.promisify(fs.readFile);
const port = 5050
// Define a folder to store the html files
const publicDir = path.join(__dirname, 'public');
const server = http.createServer(async function (req, res) {
// Read the filenames in your public folder
const allFiles = await fsReaddir(publicDir);
// Optionally filter out any files with another extension than html
const htmlFiles = allFiles.filter(fileName => /\.html$/.test(fileName))
// Parse the requested url
const q = url.parse(req.url, true);
console.log('Requested: ' + q.pathname);
// If no path is given, default to index.html
if(q.pathname === '/') {
console.log('Falling back to index')
const data = await fsReadFile(path.join(publicDir, 'index.html'));
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data.toString());
res.end();
return;
}
// Loop through all html files
for(const htmlFile of htmlFiles) {
const requestedPath = path.join(publicDir, q.pathname) + '.html';
const actualPath = path.join(publicDir, htmlFile);
// Check for a matching file
if(requestedPath === actualPath) {
console.log('Found match :-)');
// It did match, so read the data of the file and respond
const data = await fsReadFile(requestedPath);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data.toString());
res.end();
return;
}
}
console.log('Page not found...');
// No mathces were found, so respond with 404
const data = await fsReadFile(path.join(publicDir, '404.html'));
res.writeHead(404, {'Content-Type': 'text/html'});
res.write(data);
res.end();
}).listen(port);