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

2017-03-14  本文已影响21人  Realank

File System

fs module is a encapsulation of file operations.

fs.readFile [Most commonly used]

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

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:

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)])


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)])

上一篇 下一篇

猜你喜欢

热点阅读