利用 http 模块开始写简单的web服务。

模块:

const http=require('http');
const fs=require('fs');
const path=require('path'); function startServer() {
let onRequest=function (req,res) {
console.log('recived a request.');
res.writeHead(200,{'Content-Type':'text/html'}); let wwwdir= path.resolve(__dirname,'../www');
// console.log(wwwdir);
let readStream = fs.createReadStream(wwwdir+'/bbb.html');
readStream.pipe(res);
}; let server=http.createServer(onRequest);
server.listen(80,'192.168.1.101');
}; exports.startServer = startServer;

调用者,APP,使用两行就开启了一个简单的web服务。

let server=require('./mod_server');

server.startServer();

单文件版路由,响应了几个不同的页面:

const http = require('http');
const fs = require('fs');
const path = require('path'); let wwwdir = path.resolve(__dirname, '../www'); let onRequest = function (req, res) {
console.log('recived a request. ' + req.url);
if (req.url === '/' || req.url === '/home') {
res.writeHead(200, {'Content-Type': 'text/html;charset=UTF-8'});
let readStream = fs.createReadStream(wwwdir + '/index.html');
readStream.pipe(res);
} else if (req.url === '/about') {
res.writeHead(200, {'Content-Type': 'text/html;charset=UTF-8'});
let readStream = fs.createReadStream(wwwdir + '/about.html');
readStream.pipe(res);
} else if (req.url === '/api') {
res.writeHead(200, {'Content-Type': 'application/json'});
let jsonObj = {
name: "alex",
email: 'abc@gg.com',
age: 32
};
// console.log(JSON.parse(jsonStr)); // 反序列化
res.end(JSON.stringify(jsonObj));
} else {
res.writeHead(404, {'Content-Type': "text/html;charset=utf8"});
res.write('抱歉 404 ,你要的页面没找到.');
}
;
}; let server = http.createServer(onRequest);
server.listen(8001, 'localhost');

分开为独立文件的 web server

一、server.js

const http = require('http');

function startServer(route, handle) {
let onRequest = function (request, response) {
console.log('Request received ' + request.url);
// 传递到 route 函数
route(handle, request.url, response);
}; let server = http.createServer(onRequest); server.listen(, '127.0.0.1');
console.log('Server started on 127.0.0.1:8001');
} module.exports.startServer = startServer;

二、router.js

const fs = require('fs');
const path = require('path'); let wwwdir = path.resolve(__dirname, '../www'); function route(handle, pathname, response) {
console.log('Routing a request for ' + pathname);
// 判断 handle中是否有对应的 pathname 函数
if (typeof handle[pathname] === 'function') {
handle[pathname](response); // response作为参数传递到 handle 函数
} else {
response.writeHead(, {'Content-Type': 'text/html'});
fs.createReadStream(wwwdir + '/404.html', 'utf8').pipe(response);
}
} module.exports.route = route;

三、handler.js

const fs = require('fs');
const path = require('path'); let wwwdir = path.resolve(__dirname, '../www'); function home(response) {
response.writeHead(, {'Content-Type': 'text/html'});
fs.createReadStream(wwwdir + '/index.html', 'utf8').pipe(response);
} function review(response) {
response.writeHead(, {'Content-Type': 'text/html'});
fs.createReadStream(wwwdir + '/about.html', 'utf8').pipe(response);
} function api_records(response) {
response.writeHead(, {'Content-Type': 'application/json'});
let jsonObj = {
name: "Alex",
passwd: "",
email: 'aaa@cc.com',
age:
};
response.end(JSON.stringify(jsonObj));
} module.exports = {
home: home,
review: review,
api: api_records
};

四、app.js 主程序,模块方式调用前面的三个文件即可

const server = require('./server');
const router = require('./router');
const handler = require('./handler'); let handle = {};
handle["/"] = handler.home;
handle['/home'] = handler.home;
handle['/review'] = handler.review;
handle['/api'] = handler.api; server.startServer(router.route, handle);

最近学习的 Node.js 之 http的更多相关文章

  1. Docker学习之——Node.js+MongoDB+Nginx环境搭建(一)

    最近在学习Node.js相关知识,在环境搭建上耗费了不少功夫,故此把这个过程写下来同大家分享一下,今天我先来介绍一下Docker,有很多人都写过相关知识,还有一些教程,在此我只想写一下,我的学习过程中 ...

  2. 方便大家学习的Node.js教程(一):理解Node.js

    理解Node.js 为了理解Node.js是如何工作的,首先你需要理解一些使得Javascript适用于服务器端开发的关键特性.Javascript是一门简单而又灵活的语言,这种灵活性让它能够经受住时 ...

  3. 学习笔记——node.js

    node.js的作用在于,号称可以让服务器支持更多的连接.比如说,php + apche可以让服务器支持4000个并发连接,那么node.js + apche可以让服务器支持并发几万个. 为什么这么牛 ...

  4. Node.js学习(Node.js基础)

    1.开发环境搭建 v8引擎是作为解析JavaScript程序来运行的 nodejs是一个高性能的,第一个体现在他的JavaScript解析速度很快,v8引擎性能很高,第二个事件驱动和非阻塞 2.全局对 ...

  5. Node.js学习笔记——Node.js开发Web后台服务

    一.简介 Node.js 是一个基于Google Chrome V8 引擎的 JavaScript 运行环境.Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效.Node.j ...

  6. 让我们一起学习《Node.js入门》一书吧!

    Node.js入门 读完本书之后,你将完成一个完整的web应用,该应用允许用户浏览页面以及上传文件. 里面对一些知识的讲解,让你略窥Node.js的门径.最好一段代码一段代码的写下来,我的习惯是手里拿 ...

  7. 最近学习的 Node.js 基础:安装、环境配置、forever

    最近工作中,因为某某某某原因,需要用到Node.js  . 发现在很多方面和python很像,比如generator / yield ,比如模块的使用方式,比如http模块. 先安装个环境,windo ...

  8. 从零开始学习渗透Node.js应用程序

    本文来源于i春秋学院,未经允许严禁转载 0x01 介绍 简单的说 Node.js 就是运行在服务端的 JavaScript.Node.js 是一个基于Chrome JavaScript 运行时建立的一 ...

  9. vue学习之node.js

    Node.js是一个Javascript运行环境(runtime environment),发布于2009年5月,由Ryan Dahl开发,实质是对Chrome V8引擎进行了封装.本文详细介绍了No ...

  10. nodejs学习笔记Node.js 调试命令

    3.4  调试        47  下面是一个简单的例子: $ node debug debug.js < debugger listening on port 5858 connecting ...

随机推荐

  1. 实验八 <FBG> 基于原型的团队项目需求调研与分析

    <FBG>团队项目原型设计:http://www.cnblogs.com/ymm3/p/9012534.html GitHub的链接地址:https://github.com/FBGfbg ...

  2. postgis 随笔

    一.表的定义:    对于任何一种关系型数据库而言,表都是数据存储的最核心.最基础的对象单元.现在就让我们从这里起步吧.    1. 创建表:    CREATE TABLE products (   ...

  3. (最完美)红米手机5的Usb调试模式在哪里打开的教程

    就在我们使用安卓手机接通PC的时候,或者使用的有些app比如我们企业营销部门就在使用的app引号精灵,之前老版本就需要开启usb开发者调试模式下使用,现就在新版本不需要了,如果手机没有开启usb开发者 ...

  4. spring boot2 kafka

    一.软件版本 1.linux:centos6 2.zookeeper:zookeeper-3.4.1 3.kafka:kafka_2.12-2.2.0 4.jdk:1.8 5.instelliJ Id ...

  5. flex属性介绍

  6. VUE初体验篇-安装

    现代前端框架大行其道,讲前端思想从操作dom的阶段,升级到操作数据的阶段.vue作为三大前端框架之一,其中平缓的学习曲线,让好多前端新手非常喜欢,应用也越来越广泛.虽然其他两个框架有facebook, ...

  7. EF6中执行Sql语句

    EF中提供了两个方法,一个是执行查询的Sql语句SqlQuery,另外一个是执行非查询的语句ExecuteSqlCommand.SqlQuery有两种形式的,一种是泛型的,一种是非泛型的.比如我们要在 ...

  8. Nginx配置文件及模块解析

    一.Nginx是什么? Nginx是一个基于c语言开发的高性能http服务器及反向代理服务器.由俄罗斯的程序设计师Igor Sysoev所开发,官方测试nginx能够支支撑5万并发链接,并且cpu.内 ...

  9. 记一次tomcat运行起来了但是项目没起来的问题

    解决办法是: 先是tomcat的conf文件夹下的servel.xml中这两个值改成false. 然后重新运行maven的package打包,再运行项目就行了.

  10. C++标准模板库(STL)之Stack

    1.Stack的常用用法 stack:栈,一个后进先出的容器. 1.1.stack的定义 加上头文件#include<stack>和using namespace std; stack&l ...