一、Node.js应用的组成
-
引入模块:var http =
require
(‘http’); -
创建服务器:服务器可以监听客户端的请求,类似于Apache、Nginx等HTTP服务器。
http.createServer(function (request, response) { // 发送 HTTP 头部 // HTTP 状态值: 200 : OK // 内容类型: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // 发送响应数据 "Hello World" response.end('Hello World\n'); }).listen(8888); // 终端打印如下信息 console.log('Server running at http://127.0.0.1:8888/');
-
接受请求与响应请求:客户端使用浏览器或者服务器发送HTTP请求,服务器接收请求后返沪响应数据。
浏览器访问http://127.0.0.1:8888
二、npm的使用
-
查看版本号
npm -v
-
升级npm版本
npm install npm -g
-
使用淘宝镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm install [name]
-
安装模块
npm install <Module Name> -g -g:全局安装,不加为本地安装
安装好之后,express 包就放在了工程目录下的 node_modules 目录中,因此在代码中只需要通过 require(‘express’) 的方式就好,无需指定第三方包路径。
-
查看安装信息
npm list -g
-
查看某个模块的版本号
npm list <Module Name>
-
使用package.json
位于模块的目录下,用于定义包的属性。express 包的 package.json 文件如位于 node_modules/express/package.json。
属性说明:属性 描述 name 包名。 version 包的版本号。 description 包的描述。 homepage 包的官网 url 。 author 包的作者姓名。 contributors 包的其他贡献者姓名。 dependencies 依赖包列表。如果依赖包没有安装,npm 会自动将依赖包安装在 node_module 目录下。 repository 包代码存放的地方的类型,可以是 git 或 svn,git 可在 Github 上。 main main 字段指定了程序的主入口文件,require(‘moduleName’) 就会加载这个文件。这个字段的默认值是模块根目录下面的 index.js。 keywords 关键字 -
卸载模块
npm uninstall express
-
更新模块
npm update express
-
搜索模块
npm search express
-
创建模块
$ npm init Press ^C at any time to quit. name: (node_modules) runoob # 模块名 version: (1.0.0) description: Node.js 测试模块(www.runoob.com) # 描述 entry point: (index.js) test command: make test git repository: https://github.com/runoob/runoob.git # Github 地址 keywords: author: license: (ISC) About to write to ……/node_modules/package.json: # 生成地址
在npm资源库注册用户(使用邮箱注册)
$ npm adduser
发布模块
$ npm publish
撤销自己发布过的某个版本代码
$ npm unpublish <package>@<version>
-
清空npm本地缓存,用于对付使用相同版本号发布新版本代码的人。
$ npm cache clear