NodeJs常用核心模块简介

NodeJs常用核心模块简介

fs 文件管理

fs 模块提供了异步和同步2个版本 fs.readFile() fs.readFileSync()
1.写入文件内容

fs.writeFile(‘test.txt’, ‘Hello Node’ , [encoding], [callback]);

2.追加写入

fs.appendFile(‘test.txt’,‘Hello Node’,[encoding],[callback]);

3.文件是否存在

fs.exists(‘test.txt’,[callback]);

4.读取文件内容

fs.readFile(‘test.txt’, [encoding], [callback]);

5.修改文件名

fs.rename(旧文件,新文件,[callback]);

6.移动文件. 没有专门函数,通过修改文件名可以达到目的

fs.rename(oldPath,newPath,[callback]);

7.删除文件

fs.unlink(‘test.txt’, [callback]);

8.创建目录

fs.mkdir(路径, 权限, [callback]);
路径:新创建的目录。
权限:可选参数,只在linux下有效,表示目录的权限,默认为0777,表示文件所有    者、文件所有者所在的组的*用户、*所有用户,都有权限进行读、写、执行的操作。

9.删除目录

fs.rmdir(path, [callback]);

10.读取目录. 读取到指定目录下所有的文件

fs.readdir(path, [callback]);

11.打开文件

fs.open(path,flags, [mode], [callback(err,fd)])

12.关闭文件

fs.close(fd, [callback(err)])

13.读取文件

fs.read(fd,buffer,offset,length,position,[callback(err,     bytesRead, buffer)])

14.写入文件

fs.writeFile(filename, data,[encoding],[callback(err)])

15.修改文件时间戳

fs.utimes(path, atime, mtime, [callback(err)])

url 文件管理

1 .解析url - 条件解析

url.parse(‘http://www.baidu.com?page=1’,true);
结果如: { protocol: ‘http:’,
slashes: true,
auth: null,
host: ‘www.baidu.com’,
port: null,
hostname: ‘www.baidu.com’,
hash: null,
search: ‘?page=1’,
query: { page: ‘1’ },
pathname: ‘/’,
path: ‘/?page=1’,
href: ‘http://www.baidu.com/?page=1’ }

2.解析url,返回一个json格式的数组

url.parse(‘http://www.baidu.com’);
结果如: { protocol: ‘http:’,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: ‘www.baidu.com’,
path: ‘www.baidu.com’,
href: ‘http://www.baidu.com’ }

3.格式化为url. 将json数组逆向成url

url.format({
protocol: ‘http:’,
hostname:‘www.baidu.com’,
port:‘80’,
pathname :’/news’,
query:{page:1}
});
结果如: http://www.baidu.com/news?page=1

4.封装路径

url.resolve(‘http://example.com/’, ‘/one’)  // 'http://example.com/one’
url.resolve(‘http://example.com/one’, ‘/two’) // ‘http://example.com/two’

path 路径管理

1.格式化路径. 将不符合规范的路径经过格式化转换为标准路径,解析路径中的.与…外,还能去掉多余的斜杠

path.normalize(’/path///normalize/hi/…’);
结果如: ‘/path/normalize/’ 标准化之后的路径里的斜杠在Windows系统下    是,而在Linux系统下是/

2.组合路径

path.join(’///you’, ‘/are’, ‘//beautiful’);
结果如:  ‘/you/are/beautiful’

3.返回路径中的目录名

path.dirname(’/foo/strong/cool/nice’);
结果如: ‘/foo/strong/cool’

4.返回路径最后一部分,还可以排除指定字符串

path.basename(’/foo/strong/basename/index.html’);
path.basename(’/foo/strong/basename/index.html’,’.html’);
结果如: index.html 和 index

5.返回路径后缀

path.extname(‘index.html’);
结果如: .html

Query String 字符串转换

1.序列化对象.将对象类型转换成一个字符串类型(默认的分割符(“&”)和分配符(“=”))

querystring.stringify({foo:‘bar’,cool:[‘xux’, ‘yys’]});
结果如: foo=bar&cool=xux&cool=yys

 重载1: querystring.stringify({foo:‘bar’,cool:[‘xux’,     ‘yys’]},’*’,’$’);
结果如: foo$bar*cool$xux*cool$yys

2.反序列化

querystring.parse(‘foo@bar$cool@xux$cool@yys’,’@’,’$’);
结果如: { foo: ‘bar’ ,  cool: [‘xux’, ‘yys’] }

http HTTP

2个方法

http.createServer([requestListener])  创建HTTP服务器
http.createClient([port], [host])     创建HTTP客户端
http.Server

由 http.createServer 创建所返回的实例

http.Server 事件

request 客户端请求到来
提供2个参数: req, res 分别是http.ServerRequest 和 http.ServerResponse 的实例.表示请求和响应消息

connection TCP建立连接时触发
提供1个 socket 参数 net.Socket 实例

close 服务器关闭时触发
无参数

还有checkContinue 、 upgrade 、 clientError 等事件. request 经常使用,所以包含在了 createServer函数中

http.ServerRequest 对象

HTTP请求的消息, 一般由 http.Server的 request 事件发送

属性:
complete          客户端请求是否已经发送完成
httpVersion      HTTP 协议版本,通常是 1.0 或 1.1
method          HTTP 请求方法,如 GET、POST、PUT、DELETE 等
url              原始的请求路径,例如 /static/image/x.jpg 或 /    user?name=byvoid
headers          HTTP 请求头
trailers          HTTP 请求尾(不常见)
connection      当前 HTTP 连接套接字,为 net.Socket 的实例
socket          connection 属性的别名
client          client 属性的别名

GET : 的请求是直接嵌入路径中的. 解析?后面的路径就行了. url 模块中 parse 函数提供了这个功能

POST :

**HTTP 请求分: 请求头.  请求体**
http.ServerRequest 提供3个事件控制请求体传输
data:    请求体数据来到时. 参数 chunk 表示接收到的数据
end:    请求体数据传输完成时
close    用户当前请求结束时


    var post = '';
    req.on('data', function(chunk) {    post += chunk;        });
    req.on('end', function() {    post =     querystring.parse(post);
    res.end(util.inspect(post));});
http.ServerResponse 对象

http.ServerResponse是返回给客户端的信息,决定了用户最终看到的结果. 有3个重要的成员函数. 用于响应头,响应内容以及结束请求

1.向客户端发送响应头

res.writeHead(statusCode, [headers])
statusCode, 是HTTP状态码. 如200,404.

headers 类似数组的对象,表示响应头的每个属性
{
“Content-Type”: “text/html”,
“Connection”: “keep-alive”
}

2.发送响应内容, 如果是字符串,需要制定编码方式, 默认 utf-8

res.write(data, [encoding])

3.结束响应,告知客户端所有响应完成. 此函数必须调用一次

res.end([data] , [encoding] )

事件

挂接模块

var EventEmitter = require(‘events’).EventEmitter;

1.实例化一个EventEmitter对象

var event = new EventEmitter();

2.注册事件

emitter.on( ‘Event_Name’ , callBack_Fun )
emitter.once( ‘Event_Name’ , callBack_Fun )    //注册一个单次监听器,触发一次后立刻解除

3.发射事件

event.emit(‘Event_Name’ , 参数1,参数2);

4.移除事件

emitter…removeListener(‘Event_Name’ , callBack_Fun)
emitter.removeAllListeners(  [‘Event_Name’] )    //如果指定了事件名,就移除指定的,否则移除所有事件

模块和包

Node.js 的模块和包机制的实现参照了 CommonJS 的标准,但并未完全遵循。

#### 包
包是在模块基础上更深一步的抽象, 类似于 c/c++ 的函数库.
Node.js 包是一个目录. 其中包含一个JSON格式的说明文件 package.json
CommonJS 规范特征:
->   package.json 必须在包的顶层目录下
->   二进制文件在bin目录下
->   JavaScript代码在lib目录下
->   文档应该在doc目录下
->   单元测试在test目录下



#### require('Modile_Name')     
功能:    加载其他模块
说明:    不会重复加载以加载的模块


#### exports.setName
功能:    公开一个模块中的函数或对象
说明:    exports 本身仅仅是一个普通的空对象,即 {}. 所以 exports.函数      就是给它加了函数
module.exports  则是用一个对象取代 exports  对象. (不可以对     exports 直接赋值替代此功能)


方式1:
//使用
exports.SayName = function(thyName) {console.log(thyName)}; 
//调用
var test = require('./fileName');
test.SayName('XueYou');

方式2:
    //使用
    function hello(){
     var name;
    this.setNam(){};
    this.SayName(){};
    }
    module.exports = hello;
    //调用
    var test = require('./fileName');
    test = new test();    //注意因为是对象,所以要new
    test.SayName();
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2015-2021 魏姣
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信