zoukankan      html  css  js  c++  java
  • NodeJS学习笔记(五) fs,http模块

    Fs模块

    在看nodejs介绍的过程中,nodejs对自己的异步I/O是重点突出的说明的。在fs模块中,nodejs提供了异步和同步两种读写方式

    Fs.readFile

    这个方法是底层fs.read方法和fs.open方法的封装。

    fs.readFile(filename, [options], callback)

    • filename String
    • options Object
      • encoding String | Null default = null
      • flag String default = 'r'
    • callback Function

    上述代码是直接从API中拷贝过来的。其中options是一个对象,对象里面有encoding和flag。Flag在fs.open方法中讲述;在API中,中括号里面的参数是可以缺省的

    回调函数callback的形式如:function(err,data){},其中,err是一个Error对象,没有发生错误,err的值为null,或undefined。Data是文件的内容,这里需要注意,如果options缺省或者没有制定options里面的encoding,这个dataIU是一个Buffer形式表示的二进制数据,如果指定为utf-8,Data中的内容就是通过编码解析后的字符串。这里有一篇深入一点的文章,有想去的朋友可以去阅读。深入浅出Node.js(五):初探Node.js的异步I/O实现

    建立测试文件:

    1. var fs = require('fs');
    2.  
    3. fs.readFile('C:/tmp/mylog.txt', function(err,data){
    4.    if(err){
    5.       console.error(err);
    6.    }else{
    7.       console.log(data);
    8.    }
    9. });

    上面是没有添加编码的方式读取文档,显示结果如下

    fs.readFileSync(filename, [options])

    Synchronous version of fs.readFile. Returns the contents of the filename.

    Fs.readFile()的同步版本。使用法同readfile类似,但是这里没有err,所以需要使用try,catch步骤并处理异常。

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

    Asynchronous file open. See open(2). flags can be:

    • 'r' - Open file for reading. An exception occurs if the file does not exist.
    • 'r+' - Open file for reading and writing. An exception occurs if the file does not exist.
    • 'rs' - Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache.

      This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it.

      Note that this doesn't turn fs.open() into a synchronous blocking call. If that's what you want then you should be using fs.openSync()

    • 'rs+' - Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs'about using this with caution.
    • 'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
    • 'wx' - Like 'w' but fails if path exists.
    • 'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
    • 'wx+' - Like 'w+' but fails if path exists.
    • 'a' - Open file for appending. The file is created if it does not exist.
    • 'ax' - Like 'a' but fails if path exists.
    • 'a+' - Open file for reading and appending. The file is created if it does not exist.
    • 'ax+' - Like 'a+' but fails if path exists.

    这里flags的用法和linux中的文件读写权限相同。回调函数如function(err,fd).fd为一个文件描述符。通常配合fs.read方法使用

    fs.read(fd, buffer, offset, length, position, callback)

    通常情况下不使用这个方法的,比较低层,用起来也不太方便。贴上开发指南中的例子:

    1. var fs = require('fs');
    2. fs.open('C:/tmp/mylog.txt', 'r', function(err, fd) {
    3.   if (err) {
    4.     console.error(err);
    5.     return;
    6.   }
    7.   var buf = new Buffer(8);
    8.   fs.read(fd, buf, 0, 8, null, function(err, bytesRead, buffer) {
    9.     if (err) {
    10.       console.error(err);
    11.       return;
    12.     }
    13.     console.log('bytesRead: ' + bytesRead);
    14.     console.log(buffer);
    15.   })
    16. });

    结果:

    如代码段第8行。读取了0-8为字节的文件流。

    http模块

    在nodejs中封装了HTTP服务器和HTTP客户端。

    http.Server

    这里只是熟悉nodejs中的http模块的API,一般在开发过程中使用的是第三方的框架,比如说Express。其中封装了更为简单的构建http服务器的API。

    1. var http = require('http');
    2. var server = new http.Server();
    3. server.on('request', function(req, res) {
    4.   res.writeHead(200, {'Content-Type': 'text/html'});
    5.   res.write('<h1>Node.js</h1>');
    6.   res.end('<p>Hello World</p>');
    7. });
    8. server.listen(3000);
    9. console.log("HTTP server is listening at port 3000.");

    上述代码建立了一个建议的http服务器,监听本地的3000端口。

    代码段中第三行,为server添加了request事件。当客户端的request请求时,调用回调函数,回调函数中的req和res对象分别是http.ServerRequest对象和http.ServerResponse对象。同servlet中获取的对象类似。其中http.Server继承了EventEmitter。其中还有许多响应事件,如下图所示:


    获取GET请求和POST请求

    GET请求:

    1. var http = require('http');
    2. var url = require('url');
    3. var util = require('util');
    4.  
    5. http.createServer(function(req, res) {
    6.   res.writeHead(200, {'Content-Type': 'text/plain'});
    7.   res.end(util.inspect(url.parse(req.url, true)));
    8. }).listen(3000);

    我们在本地的localhost添加了对3000端口的监控,当浏览器输入http://localhost:3000/?username=wenlonghor&password=admin 模仿我们登录的过程,浏览器结果:

    请求的键值对在query里面封装着呢,我们可以使用res.query.name和res.query.password来获取参数

    POST请求:

    1. var http = require('http');
    2. var querystring = require('querystring');
    3. var util = require('util');
    4.  
    5. http.createServer(function(req, res) {
    6.   var post = '';
    7.   req.on('data', function(chunk) {
    8.     post += chunk;
    9.   });
    10.   req.on('end', function() {
    11.     post = querystring.parse(post);
    12.     res.end(util.inspect(post));
    13.   });
    14. }).listen(3000);

    我们是用一个表单来试验POST的请求过程:

    1. //表单代码
    2. <form methon='post' action='localhost:3000'>
    3.    <input type='text' name='username'/>
    4.    <input type='password' name='admin'/>
    5.    <input type='submit value='submit'/>
    6. </form>

    这个代码返回的post对象是空的,还没有找到原因,等找到原因回来修改文章

    http客户端暂时不想写了,了解http服务器端即可。

  • 相关阅读:
    samba安装和配置
    linux下打包命令的使用
    Linux目录结构简析
    Linux服务器的安装
    linux下定时任务设置
    创建表空间并授权
    selenium2.0(WebDriver) API
    selenium + python之元素定位
    Linux实战教学笔记13:定时任务补充
    Linux实战教学笔记11:linux定时任务
  • 原文地址:https://www.cnblogs.com/wenlonghor/p/3311759.html
Copyright © 2011-2022 走看看