app.js
const http = require('http');
const fs = require('fs');
const hljs = require('highlight.js'); // https://highlightjs.org/
hljs.registerLanguage('javascript', require('highlight.js/lib/languages/javascript'));
// 暴力假如样式文件
let hljsCss = fs.readFileSync('node_modules/highlight.js/styles/github.css')
hljsCss = `<head><style>
${hljsCss.toString()}
body {text-align: center;}
pre {text-align: start;}
</style></head>`
// 通常的默认值
const md = require('markdown-it')({
html: true, // markdown中启用html标签
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(str, { language: lang, ignoreIllegals: true }).value;
}
return ''; // 使用额外的默认转义
}
});
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
if (req.url === '/text') {
fs.readFile('./输入效果.html', (err, data) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(data.toString());
})
} else if (/.md$/.test(req.url)) {
try {
fs.readFile('.'+req.url, (err, data) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
let str = data.toString()
// 修复markdown-it插件问题, 换行没生效
str = str.replaceAll(/\n/g, ' \n')
str = hljsCss + md.render(str)
res.end(str);
})
} catch (error) {
console.error('markdown错误: ', error)
}
} else if (req.url === '/img-dmjg') {
fs.readFile('./img-dmjg.html', (err, data) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(data.toString());
})
} else if (['/image.png', '/favicon.ico'].includes(req.url)) {
// 读取图片文件
fs.readFile('image.png', (err, imageContent) => {
// 设置响应头
res.writeHead(200, { 'Content-Type': 'image/jpeg' });
// 将图片发送给客户端
res.end(imageContent);
})
} else {
fs.readFile('./index.html', (err, data) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(data.toString());
})
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
package.json
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "w5han",
"license": "ISC",
"dependencies": {
"highlight.js": "^11.8.0",
"markdown-it": "^13.0.1"
}
}