在移动端页面开发过程中,如果没有使用webpack等工具,而是单纯的靠一个个HTML文件开发时,那么真机查看页面则会成为一个问题,需要借助第三方的工具,比如 XAMPP,虽然XAMPP工具很强大,但使用时却需要做很多工作,不太方便,这是可以换一个思路,使用NodeJS手写一个服务器来访问我们的目标文件。
实现思路
所需模块
使用url模块和path模块获取所有文件的相对路径后,利用fs模块解析文件的内容,然后将文件内容发送到页面
具体实现代码如下
/**server.js*/
const http = require('http')
const fs = require('fs')
const url = require("url")
const path = require('path')
http.createServer((req, res) => {
let pathname = url.parse(req.url).pathname;
let realPath = path.join(__dirname, pathname)
console.log(req.url)
fs.readFile(realPath, (err, data) => {
if (err) {
// console.log(err)
res.writeHead(200, {
'content-type': 'text/html;charset="utf-8'
});
res.write('请在连接后拼上你要访问的文件名后重新打开')
res.end()
} else {
res.write(data)
res.end()
}
})
}).listen(3000, () => {
console.log('服务已开启:http://localhost:3000/daylyreport.html')
})
注意事项
server.js 文件最好放在根目录下,这样服务开启后可以更好的访问文件,实例代码中的 daylyreport.html 和 server.js 同在根目录,所以可以写成 http://localhost:3000/daylyreport.html
・ᴗ・ 觉得不错就点个赞吧!