20160809 笔记 nodejs文件和URL操作

复习:编写简单的http服务器

const http = require("http");
const ip = "192.168.25.128";
const port = 3000;

http.createServer((req,res)=>{
res.writeHead(200,{'content-type:':'text/html'});
res.write('hello');
res.end();
}).listen(port,ip,()=>{
console.log('server start');
});

改写程序

url地址访问
const http = require("http");
const url = require("url");
const ip = "192.168.25.128";
const port = 3000;
var f =function(req,res){
  var pathname = url.parse(req.url).pathname;
  res.write(pathname);
  res.end();
}
var f2 = function(){
  console.log('server');
}
http.createServer(f).listen(port,ip,f2);
文件操作

touch 创建空文件

获取文件内容
const http = require("http");
const url = require("url");
const fs = require("fs");
const ip = "192.168.25.128";
const port = 3000;

//fs.readFile('a.txt',(err,data)=>{
    // if(err)throw err;
    // console.log(data.toString());
// });
var data = fs.readFileSync('a.txt');//读取文件内容
var f =function(req,res){
    var pathname = url.parse(req.url).pathname;
  res.write(pathname);
    res.write(data.toString());
  res.end();
}
var f2 = function(){
  console.log('server');
}
http.createServer(f).listen(port,ip,f2);

根据请求判断访问的模板

const http = require("http");
const url = require("url");
const fs = require("fs");
const ip = "192.168.25.128";
const port = 3000;
var server = new http.Server();
server.listen(port,ip);
server.on('req',function(req,res) {
    var pathname = url.parse(req.url).pathname;
    // var userurl = url.parse(pathname);

    switch (pathname) {
        case '' || '/':
            fs.readFile('./index.html',function(err,content) {
                if (err) {
                    console.log(err);
                }else {
                    res.writeHead(200, {'Content-Type':'text/html:charset=utf-8'});
                    res.write(content);
                    res.end();
                }
            });
            break;
        default:

    }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值