美文网首页
Node.js学习笔记3——文件系统

Node.js学习笔记3——文件系统

作者: Realank | 来源:发表于2017-03-14 11:40 被阅读21次

File System

fs module is a encapsulation of file operations.

fs.readFile [Most commonly used]

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

  • filename: file name to read
  • encoding: optional, for character encoding
  • callback: to receive the content of the file.

If we encoding is omitted, datas will be passed as binar with Buffer style.
If we set a encoding, it will pass datas with given encoding

var fs = require('fs');
fs.readFile('content.txt', function(err, data) { 
    if (err) {
        console.error(err); 
    } else {
        console.log(data);
    }
});

//<Buffer 54 65 78 74 20 e6 96 87 e6 9c ac e6 96 87 e4 bb b6 e7 a4 ba e4 be 8b>

fs.readFile('content.txt','utf-8', function(err, data) { 
    if (err) {
        console.error(err); 
    } else {
        console.log(data);
    }
});

//Text 文本文件示例

fs.open

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

flags:

  • r : read
  • r+ : read write
  • w : write
  • w+ : read write
  • a : add read
  • a+ : add read write

mode:
config the file authority, default is 0666, POSIX standard

callback function will pass a file descriptor fd

fs.read

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

  • fd : file descriptor
  • buffer : buffer to store read datas
  • offset : offset to write to buffer
  • length : bytes num to read
  • position : beginning position of file to read, if position is null, it will read from current file pointer position (current offset)
  • bytesRead : bytes num read
  • buffer : buffer object to store read datas

var fs = require('fs');
fs.open('content.txt', 'r', function(err, fd) { 
    if (err) {
        console.error(err);
        return; 
    }
    var buf = new Buffer(8);
    fs.read(fd, buf, 0, 8, null, function(err, bytesRead, buffer) {
        if (err) { 
            console.error(err); return;
        }
        console.log('bytesRead: ' + bytesRead);
        console.log(buffer);
    })
});

//result
//bytesRead: 8
//<Buffer 54 65 78 74 20 e6 96 87>

fs.close

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

相关文章

网友评论

      本文标题:Node.js学习笔记3——文件系统

      本文链接:https://www.haomeiwen.com/subject/cvbcnttx.html