首页 > 网站 > WEB开发 > 正文

nodeJS 菜鸟入门

2024-04-27 14:12:55
字体:
来源:转载
供稿:网友

nodeJS 菜鸟入门

从一个简单的 HTTP 服务开始旅程……

创建一个 server.js 文件,写入:

//最简单的 http 服务例子var http = require("http");http.createServer(function(request, response) {    response.writeHead(200, {"Content-Type": "text/html"});    response.write("<h1>Hi NodeJs</h1>");    response.end();}).listen(8080);console.log("成功的提示:httpd start @8080");

打开 http://localhost:8080/ 你会看到惊喜~

tips

执行: node server.js启动服务。按 Ctrl + c 结束 刚刚创建的服务。

分析该HTTP服务

  1. http服务器: Node.JS 自带的, http 模块
  2. createServer: 调用该返回的对象中的 listen 方法,对服务端口进行监听
  3. 复习下 匿名函数
匿名函数的变化
//自带的http 模块var http = require("http");function onRequest(request, response) {  //console.log("请求来了,事件响应");  response.writeHead(200, {"Content-Type": "text/plain"});  response.write("<h1>Hi NodeJs</h1>");  response.end();}http.createServer(onRequest).listen(8080);console.log("成功的提示:httpd start @8080");
扩展 事件驱动

Felix Geisend?rfer 的 Understanding node.js (理解NodeJS)

  • php: 任何时候当有请求进入的时候,网页服务器(通常是Apache)就为这一请求新建一个进程,并且开始从头到尾执行相应的PHP脚本;
  • Node.js: 事件驱动设计
  • 证明 NodeJS 的事件驱动设计: 去掉以上代码 这个注释 //console.log("请求来了,事件响应"); 启动 server.js
  • 结果: 启动服务时,输出 成功…… 执行网页请求时,输出 请求……
  • 一次http请求输出俩次事件是因为:大部分服务器都会在你访问 http://localhost:8080 /时尝试读取 http://localhost:8080/favicon.ico

模块化

把 server.js 变成一个模块:
var http = require("http");function start() {  function onRequest(request, response) {    //console.log("请求来了,事件响应");    response.writeHead(200, {"Content-Type": "text/plain"});    response.write("Hi NodeJS");    response.end();  }  http.createServer(onRequest).listen(8080);  console.log("成功的提示:httpd start @8080");}//nodejs中exports对象,理解 **module.exports** 和 **exports**exports.start = start;
理解 module.exports 和 exports :

exports 获取的所有的属性和方法,都会传递给 Module.exports但是 Module.exports 本身不具备任何属性和方法。如果, Module.exports 已经具备某些属性或方法,那么 exports 传递的属性或者方法会被忽略(失败)。

代码举例
// a.jsexports.Words = function() {    console.log('Hi');};// b.jsvar say = require('./a.js');say.words(); // 'Hi'//----分割线----// aa.jsmodule.exports = 'Wellcome';exports.words = function() {    console.log('Hi');};// bb.jsvar say = require('./aa.js');say.words(); // TypeError: Object Wellcome has no method 'words'
调用

创建 index.js 写入:

var server = require("./server");server.start();

启动: node index.js 看看吧!

牛刀小试 路由选择模块

作为 ThinkPHP 的玩家,肯定能想到 TP 的路由: 通过实例化对象来实现路由选择;现在来看看 node 是怎么来实现的:

1 、提取出请求的URL以及GET/POST参数,这里需要额外的NodeJS模块:URLquerystring

仔细看下图:

                       url.parse(string).query                                           |           url.parse(string).pathname      |                       |                   |                       |                   |                     -----   ------------------http://localhost:8080/start?foo=bar&hello=world                                ---       -----                                 |          |                                 |          |              querystring(string)["foo"]    |                                            |                         querystring(string)["hello"]

2 、帮助 onRequest()函数 找出浏览器请求的URL路径

先新建一个 router.js 写入,能够输出当前请求的路径名称

function route(pathname) {    console.log("请求路径是:" + pathname);}exports.route = route;

再扩展 server.js

var http = require("http"),    //URL模块可以读取URL、分析诸如hostname、port之类的信息    url  = require("url");//传入 route (回调函数)function start(route) {    function onRequest(request, response) {        var pathname = url.parse(request.url).pathname;        //console.log("请求 "+pathname+" ,事件");        route(pathname);        response.writeHead(200, {"Content-Type": "text/plain"});        response.write("Hi NodeJS");        response.end();    }    http.createServer(onRequest).listen(8080);    console.log("成功的提示:httpd start @8080");}exports.start = start;

最后扩展 index.js

var server = require("./server");var router = require("./router");server.start(router.route);

启动,输入 http://localhost:8080/a 结果

$ node index.js成功的提示:httpd start @8080请求路径是:/a请求路径是:/favicon.ico

扩展:

Martin Fowlers 关于依赖注入的大作

函数编程

注重:数学本质、抽象本质。重要的概念:循环可以没有(描述如何解决问题),递归(描述这个问题的定义)是不可或缺;面向对象编程是 传递对象;而在函数式编程中,传递的是函数(更专业的叫:叫做高阶函数)高阶函数:a、接受一个或多个函数输入;b、输出一个函数

其他, 行为驱动执行 (BDD) 和 测试驱动开发(TDD)

函数编程扩展阅读:

函数式编程扫盲篇Steve Yegge 名词王国中的死刑

路由处理函数

示例,创建一个 requestHandlers.js 模块

function start() {    console.log("处理请求 'start' 开启.");}function upload() {    console.log("处理请求 'upload' 开启.");}exports.start = start;exports.upload = upload;
对象传递

将一系列请求处理程序通过一个对象来传递,并且需要使用松耦合的方式将这个对象注入到 route() 函数中

1、先将这个对象引入到主文件 index.js

var server = require("./server"),    router = require("./router"),    requestHandlers = require("./requestHandlers");var handle = {};    handle["/"] = requestHandlers.start;    handle["/start"] = requestHandlers.start;    handle["/upload"] = requestHandlers.upload;server.start(router.route, handle);

2、把额外的传递参数 handle 给服务器 server.js

var http = require("http"),    url  = require("url");function start(route, handle) {    function onRequest(request, response) {        var pathname = url.parse(request.url).pathname;        console.log("请求 "+pathname+" 响应");        route(handle, pathname);        response.writeHead(200, {"Content-Type": "text/plain"});        response.write("Hi NodeJS");        response.end();    }    http.createServer(onRequest).listen(8080);    console.log("成功的提示:httpd start @8080");}exports.start = start;

3、修改 router.js

function route(handle, pathname) {    console.log("route 请求路径:" + pathname);    if (typeof handle[pathname] === 'function') {        handle[pathname]();    } else {        console.log("找不到路径 " + pathname);    }}exports.route = route;

4、运行结果: http://localhost:8080/start

$ node index.js成功的提示:httpd start @8080请求 /start 响应route 请求路径:/start处理请求 'start' 开启.请求 /favicon.ico 响应route 请求路径:/favicon.ico找不到路径 /favicon.ico

和浏览器的互动

浏览器需要对请求作出响应。

不好的实现方式

1、将 requestHandler.js 修改为

function start() {    console.log("处理请求 'start' 开启.");    return "Hello Start";}function upload() {    console.log("处理请求 'upload' 开启.");    return "Hello Upload";}exports.start = start;exports.upload = upload;

2、将 router.js 修改为

function route(handle, pathname) {    console.log("route 请求路径:" + pathname);    if (typeof handle[pathname] === 'function') {        return handle[pathname]();    } else {        console.log("找不到路径 " + path
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表