nodejs抓取动态网页( 一个、path和url模块的确定文件的路径这就要依赖于 )
优采云 发布时间: 2022-01-05 12:11nodejs抓取动态网页(
一个、path和url模块的确定文件的路径这就要依赖于
)
<a id="nodejs_0"></a>超简单的nodejs静态网页服务器
<p>使用 nodejs 进行后端开发有一个非常方便的地方是它可以不依赖于其他的服务器软件,比如 tomcat 之类的。这里对我使用 nodejs 写的一个静态网页服务器做一个简单的总结
在这里使用到了以下模块:
http:相应基本的 http 请求fs:读取文件并返回path:获取文件的路径url:解析 url
<a id="_10"></a>第一步,创建一个最基本的服务器
let http = require('http');
let server = http.createServer(function(request, response){
response.end();
})
server.listen(8000);
</p>
这个服务器正在*敏*感*词*8000端口的请求,但是由于没有处理功能,所以只是一个空架子
第二步,确定文件的路径
这一步取决于我们的 fs、path 和 url 模块
首先,我们使用path模块来确定静态页面和资源文件所在的目录:
__dirname 可以直接获取当前目录的绝对路径。对于下图所示的目录结构,可以编写如下语句
|- serve.js
|- public
|- index.html
|- CSS
|- JS
|- Image
let staticPath = path.resolve(__dirname, 'public');
然后,我们需要通过 url 模块获取我们要访问的页面,并使用我们的 url 模块进行解析
同时,我们在访问目录时,通常是直接访问index.html。我们也可以访问知青默认打开的页面:
let pathname = url.parse(request.url, true).pathname;
if (pathname == '/') {
pathname = '/index.html';
}
这样就可以得到想要访问的页面的绝对路径
let filePath = path.join(staticPath, pathname);
第三步是读入文件并做出相应的响应
读取文件依赖于 fs 模块。值得一提的是,我们可以通过fs.readFileSync同步读入,也可以通过fs.readFile异步读入,性能相对较高
fs.readFile的回调函数有两个参数,第一个参数是一个错误,第二个参数是一个String或者一个Buffer:
//异步读取file
fs.readFile(filePath, function (err, data) {
if (err) {
console.log(err);
// 如果找不到文件资源报错可以显示准备好的 404页面
let errPath = path.join(staticPath, '/404.html');
fs.readFile(errPath, (err, data404) => {
if (err) {
console.log('error');
response.write('404 Not Found');
response.end();
} else {
response.writeHead(404, { "Content-Type": "text/html;charset='utf-8'" });
response.write(data404);
response.end();
}
})
} else {
console.log('');
response.write(data);
response.end();
}
})
如果有事先准备好的错误页面,可以在文件读取错误时显示,如上例
结束
结合以上内容得到的代码如下,运行在node环境下,可以在8000端口访问与serve.js同级的public目录下的静态页面!
const http = require('http')
const fs = require('fs')
const url = require('url')
const path = require('path')
let server = http.createServer(function (request, response) {
//获取输入的url解析后的对象
let pathname = url.parse(request.url, true).pathname;
if (pathname == '/') {
pathname = '/index.html';
}
//static文件夹的绝对路径
let staticPath = path.resolve(__dirname, 'public');
//获取资源文件绝对路径
let filePath = path.join(staticPath, pathname);
console.log(filePath);
//异步读取file
fs.readFile(filePath, function (err, data) {
if (err) {
console.log(err);
// 如果找不到文件资源报错可以显示准备好的 404页面
let errPath = path.join(staticPath, '/404.html');
fs.readFile(errPath, (err, data404) => {
if (err) {
console.log('error');
response.write('404 Not Found');
response.end();
} else {
response.writeHead(404, { "Content-Type": "text/html;charset='utf-8'" });
response.write(data404);
response.end();
}
})
} else {
console.log('ok');
response.write(data);
response.end();
}
})
})
server.listen(8000)
console.log('visit http://localhost:8000')