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

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);
    }
});

//

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
//

fs.close

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

你可能感兴趣的:(Node.js学习笔记3——文件系统)