【1】Node.js Hello World! 发布静态网页

xiaoxiao2021-02-28  76

参考:http://www.cnblogs.com/qingbin-bai/p/6271388.html  (讲的非常好)

Node.js环境搭建-安装启动-npm安装扩展包

本文源码百度网盘下载

发布一个静态网页本来就几行Node.js代码,但是这里使用的是《Node.js实战》里面的开篇示例,增加了错误处理,文件缓存、函数封装的功能。其实仍然是相当容易理解的。

1 本文实现的内容:

客户通过浏览器访问:http://localhost:8080/  可以看到服务端发来的index.html文件内容“Hello World!”

2 实现的过程:

服务端只需要提供两个文件就可以实现,一个是server.js;一个是index.html文件,其中该文件内容只有Hello World!这个字符串。

3 源代码(具体文件内容如下):

server.js文件:

var http = require('http'); var fs = require('fs'); var path = require('path'); var mime = require('mime'); var cache = {}; function send404(response) { response.writeHead(404, { 'Content-Type': 'text/plain' }); response.write('Error 404: resource not found.'); response.end(); } function sendFile(response, filePath, fileContents) { //服务端返回静态文件:正确的http头;原来的lookup改为了现在的getType response.writeHead(200, { "content-type": mime.getType(path.basename(filePath)) }); console.log('sendFile content-type:' + mime.getType(path.basename(filePath)));//text/html response.end(fileContents); } function serverStatic(response, cache, absPath) { if (cache[absPath]) { sendFile(response, absPath, cache[absPath]);//从内存中返回文件给客户端浏览器 } else { fs.exists(absPath, function (exists) { if (exists) { console.log('serverStatic exists absPath:' + absPath); fs.readFile(absPath, function (err, data) { if (err) { send404(response); } else { cache[absPath] = data;//先缓存文件,为下次直接在内存中使用 sendFile(response, absPath, data);//发送文件给客户端浏览器 } }) } else { send404(response); } }) } } var server = http.createServer(function (request, response) { var filePath = false; if (request.url == '/') { console.log('createServer url / return public/index.html'); filePath = 'public/index.html'; } else { filePath = 'public' + request.url; } var absPath = './' + filePath; serverStatic(response, cache, absPath); }); server.listen(8080, function () { console.log('server listening on port 8080'); });

index.html文件:

Hello Wrold !

以上两个文件都保存为UTF-8格式

4 执行Node.js和node server.js

转载请注明原文地址: https://www.6miu.com/read-21850.html

最新回复(0)