NodeJs>------->>第一章:Node.js介绍



一:章节前言

image

二:Node.js概述

1:使用node.js能够解决什么问题

image

2:实现高性能服务器

image

3:非阻塞型I/O及事件环形机制

image

image


4:node.js适合开发的程序

image


三:node.js安装

image

image


一、Node.js 安装配置

Node.js 提供在Windows和Linux上安装, 本文将以Windows上Node最新版本v6.9.3为例来学习,不足之处还望指正:

1.  Window 上安装Node.js

image

32 位安装包下载地址 : https://nodejs.org/dist/v6.9.3/node-v6.9.3-x86.msi

64 位安装包下载地址 : https://nodejs.org/dist/v6.9.3/node-v6.9.3-x64.msi

安装步骤如下:

1.1 双击node-v6.9.3-x64.msi ,然后一直next下去

image

image

image

image

image


恭喜你安装成功啦!

2:检测PATH环境变量是否配置了Node.js

点击开始=》运行=》输入"cmd" => 输入命令"path",输出如下结果:

我们可以看到环境变量中已经包含了 D:softdevelopdevelopSoft odeJs;

检查Node.js版本

image


二:NodeJs 的 第一个简单应用:Hello World


事实上,我们的 Web 应用以及对应的 Web 服务器基本上是一样的。

在我们创建 Node.js 第一个 "Hello, World!" 应用前,让我们先了解下 Node.js 应用是由哪几部分组成的:

  1. 引入 required 模块:我们可以使用 require 指令来载入 Node.js 模块。

  2. 创建服务器:服务器可以监听客户端的请求,类似于IIS 、Apache 、Nginx 等 HTTP 服务器。

  3. 接收请求与响应请求 服务器很容易创建,客户端可以使用浏览器或终端发送 HTTP 请求,服务器接收请求后返回响应数据。

具体操作如下:

1. 创建一个网站的根目录,例如:D:softdevelopdevelopSoft odeJsDemo

2. 在根目录下创建一个js文件,例如:server.js

3. 在server.js内撸下如下代码:

  1 var http = require('http');//我们使用 require 指令来载入 http 模块,并将实例化的 HTTP 赋值给变量 http
  2 
  3 http.createServer(function (request, response) {
  4 
  5     // 发送 HTTP 头部 
  6     // HTTP 状态值: 200 : OK
  7     // 内容类型: text/plain
  8     response.writeHead(200, {'Content-Type': 'text/plain'});
  9 
 10     // 发送响应数据 "Hello World"
 11     response.end('Hello World
');
 12 }).listen(8888);//接下来我们使用 http.createServer() 方法创建服务器,并使用 listen 方法绑定 8888 端口。 函数通过 request, response 参数来接收和响应数据。
 13 
 14 // 终端打印如下信息
 15 console.log('Server running at http://127.0.0.1:8888/');

  以上代码我们完成了一个可以工作的 HTTP 服务器。

4. 使用 node 命令执行以上的代码:

  将目录指向到网站根目录下—>执行node命令运行:---->出现Server running at http://127.0.0.1:8888,证明Web服务器已经启动并成功运行了

image

4.4 打开浏览器,输入http://127.0.0.1:8888

image




四:node.js中的模块

image

  1 exports.printFoo=function(){return "foo"}

image

  1 var foo=require('./foo.js');//通过foo.js 文件路径加载foo.js模块
  2 console.log(foo.printFoo());//访问foo.js模块内的printFoo函数

image

image

image

  1  var  http =require('http');

image


image

image

五:一个简单的示例应用程序

  1 var http = require('http');
  2 http.createServer(function (req, res) {
  3   res.writeHead(200, {'Content-Type': 'text/html'});
  4   res.write('<head><meta charset="utf-8"/></head>');
  5   res.end('你好
');
  6 }).listen(1337, "127.0.0.1");
  7 console.log('Server running at http://127.0.0.1:1337/')

image

  1 var http = require('http');

image

  1 http.createServer(function (req, res) {
  2   //回调函数中的代码略
  3 })

image

  1  res.writeHead(200, {'Content-Type': 'text/html'});

image

  1   res.write('<head><meta charset="utf-8"/></head>');

image

  1 res.end('你好
');

image

  1 http.createServer(function (req, res) {
  2 //回调函数中的代码略
  3 }).listen(1337, "127.0.0.1");

image

  1 console.log('Server running at http://127.0.0.1:1337/')

    代码执行情况如下:

image


六:小结

image

原文地址:https://www.cnblogs.com/ios9/p/7490317.html