Node.js静态请求(8.9)

2016-08-10  本文已影响0人  Tarek

创建服务器

const http = require('http');
const ip = '192.168.169.129';
const port = 3000;

var f = function(req,res){
res.writeHead(200,{'Content-Type':'text/plain'});
res.write("Hello !");
res.end();
}

var f2 = function(){
console.log('server start');
}

var server = http.createServer(f);
server.listen(port,ip,f2);

添加URL内容

const http = require('http');
const ip = '192.168.169.129';
const port = 3000;
const url = require('url');

var f = function(req,res){
  var path = url.parse(req.url).pathname;
  res.write(path);
  res.end();
}

var f2 = function(){
  console.log('server start');
}

var server = http.createServer(f);
server.listen(port,ip,f2);

读取File

const http = require('http');
const ip = '192.168.169.129';
const port = 3000;
const fs = require('fs');

var f3 = function(err,data){
  console.log(data.toString());
}

fs.readFile('q.index.html',f3);

var f = function(req,res){
  res.writeHead(200,{'Content-Type':'text/html'})
  res.write("Hello Kitty !");
  res.end();
}

var f2 = function(){
  console.log('server start');
}

var server = http.createServer(f);
server.listen(port,ip,f2);

浏览器输出文件内容

const http = require('http');
const ip = '192.168.169.129';
const port = 3000;
const url = require('url');
const fs = require('fs');

var data = fs.readFileSync('./index.html');

var f = function(req,res){
  var path = url.parse(req.url).pathname;
  res.write(path);
  res.write(data.toString());
  res.end();
}

var f2 = function(){
  console.log('server start');
}

var server = http.createServer(f);
server.listen(port,ip,f2);
上一篇下一篇

猜你喜欢

热点阅读