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

参考: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++程序员Carea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值