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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • https://nodejs.org/api/documentation.html 工具模块 Assert 测试 ...
    KeKeMars阅读 6,477评论 0 6
  • 文件系统模块是一个封装了标准的 POSIX 文件 I/O 操作的集合。通过require('fs')使用这个模块。...
    保川阅读 835评论 0 0
  • //公共引用 varfs =require('fs'), path =require('path'); 1、读取文...
    才気莮孒阅读 847评论 0 1
  • Node.js 中包含一个文件系统模块,给我们提供了许多非常便利的对文件的一些操作方法。使用的时候首先需要我们导入...
    baiying阅读 690评论 0 3
  • 夜未明, 人却醒了, 也许是未曾眠; 倚窗前, 繁星未见, 不见嘈杂的车鸣声; 遥望处, 山色暗淡, 天地分色分外...
    林上的雪阅读 222评论 0 1