Nodejs学习item【入门手上】

2020-06-17 07:50:05易采站长站整理

一、 安装

首先,去http://nodejs.org 下载安装。我下的版本是0.8.14。安装很简单,下一步下一步就哦了。然后在path中配置一下安装目录即可,msi会把npm(Node Package Manager)一并装上。

这里写图片描述

我的安装目录是C:Program Files (x86)nodejs。这时使用cmd命令窗口

node -v
npm -v
命令查看下安装的版本

1.1、helloworld

在Node.js工程目录中新建一个文件hello.js,里面敲一行代码


console.log('hello, nodejs.') ;

进入命令行控制台,进入到Node.js工程目录敲node hello.js

控制台输出了“hello, nodejs.”

1.2、web版的helloworld

在Node.js工程目录中新建一个http.js,代码如下


var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write("Hello World!");
response.end();
}).listen(8000);

在命令行中启动服务,敲 node http.js

然后打开浏览器地址栏输入http://localhost:8000/,看见页面上输出Hello World! 就成功了。

node.js的版本一定和API同步

node.js的版本号有规律,偶数版本为稳定版本,奇数版本非稳定版本

2 HelloWorld代码分析

好啦,从现在开始逐行分析我们的HelloWorld。

引入模块


var http = require("http");

require方法用来引入一个模块,参数是模块的名字。比如File System模块,可以这么引入:


var fs = require("fs");

我们可以把require()方法当做全局方法使用,但实际上它更像属于某个模块的本地方法,它的文档参考这里:https://nodejs.org/api/globals.html。

require方法返回某个模块的实例,比如require(“http”)就返回一个HTTP实例。HTTP实例的参考文档在这里:https://nodejs.org/api/http.html。

我们看到,HTTP模块有一个方法createServer(),就牵涉到我们的第二行代码了。

创建服务器

HTTP模块的createServer()方法,接受一个方法作为参数,原型为:


http.createServer([requestListener])