20160809 笔记 nodejs文件和URL操作

xiaoxiao2021-02-28  95

复习:编写简单的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: } });
转载请注明原文地址: https://www.6miu.com/read-29107.html

最新回复(0)