node 创建web服务器

目前最主流的三个服务器是Apache、Nginx、IIS

node创建web服务器

如果你有一份html文件,你想打开它的时候你的操作是不是双击.html文件?这当然没问题,问题是今天我们可以有另外一种方法。

新建fml文件,文件下建立node-http.js,index.html,并复制黏贴如下对应代码:

var http = require('http');
var fs = require('fs');
var url = require('url');
// 创建服务器
http.createServer( function (request, response) {  
   // 解析请求,包括文件名
   var pathname = url.parse(request.url).pathname;
   
   // 输出请求的文件名
   console.log("Request for " + pathname + " received.");
   
   // 从文件系统中读取请求的文件内容
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
         response.writeHead(404, {'Content-Type': 'text/html'});
      }else{  
         response.writeHead(200, {'Content-Type': 'text/html'});    
         
         // 响应文件内容
         response.write(data.toString());        
      }
      //  发送响应数据
      response.end();
   });   
}).listen(4321);
console.log('Server running at http://localhost:4321/');


Hello Fengml!


终端输入:

C:\Users\admin\Desktop\fml> node node-http.js
Server running at http://localhost:4321/

浏览器输入localhost:4321/index.html
Hello Fengml!

有木有感受到像是创建了本地服务器,而你的项目也放在了本地服务器上?。这种很像通过类似hbulider/vscode编辑器访问页面。

node创建web客户端
node-client.js代码如下:
---
var http = require('http');
// 用于请求的选项
var options = {
   host: 'localhost',
   port: '4321',
   path: '/index.htm'  
};

// 处理响应的回调函数
var callback = function(response){
   // 不断更新数据
   var body = '';
   response.on('data', function(data) {
      body += data;
   });
   
   response.on('end', function() {
      // 数据接收完成
      console.log(body);
   });
}
// 向服务端发送请求
var req = http.request(options, callback);
req.end();

关闭已打开的终端,重新打开终端输入:

 C:\Users\admin\Desktop\fml> node node-http.js

然后再不关闭上个终端的前提下,重新打开一个终端(vscode中ctrl+`打开终端界面右上角点击+)

 C:\Users\admin\Desktop\fml> node node-client.js

观看两个控制台的输出

 C:\Users\admin\Desktop\fml> node node-client.js


    Hello Fengml!


---
C:\Users\admin\Desktop\fml> node node-http.js
Server running at http://localhost:4321/
Request for /index.html received.

原文地址 https://gitee.com/wangFengJ/node/tree/master/node-web

你可能感兴趣的:(node 创建web服务器)