Node常用内置模块-http

http服务器

实现一个最简单的web程序:http.js

"use strict";

var http = require("http");
var server = http.createServer(function (request,response){
    console.log(request.method+":"+request.url);
    response.writeHead(200,{"content-type":"text/html;charset=utf8"});
    response.end("<h1>Hello World!</h1>");
});
server.listen(8080);
console.log("Server is running at http://127.0.0.1:8080/");

在命令提示符下运行该程序,可以看到以下输出:

$ node hello.js 
Server is running at http://127.0.0.1:8080/

直接打开浏览器输入http://localhost:8080

同时,在命令提示符窗口,可以看到程序打印的请求信息:

GET: /
GET: /favicon.ico

文件服务器

"use strict";

var fs = require("fs");
var url = require("url");
var path = require("path");
var http = require("http");

//从命令行参数获取root目录,默认是当前目录
var root = path.resolve(process.argv[2]||".");

//创建服务器
var server = http.createServer(function(request,response){
	//获得url的path
    var filename = url.parse(request.url).pathname;
    
    //如没有path,设置默认
    if("/"==filename){filename = "index.html";}
    
    //获得对应的本地文件路径
    var filepath = path.join(root,filename);
    
    //获取文件状态:
    fs.stat(filepath,function(err,stats){
        if(!err&&stats.isFile()){
            console.log(200);
            response.writeHead(200,{"content-type":"text/html;charset=utf8"});
            fs.createReadStream(filepath).pipe(response);
        } else if(!err&&stats.isDirectory()){
            console.log(404);
            response.writeHead(404);
            //将文件源导向response
            response.end("Please open a file, not a directory");
        }else{
            console.log(404);
            response.writeHead(404);
            response.end("404 Not Found!");
        }
    })
});

server.listen(8080);
console.log("Server is running ... ");

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值