nodejs 數(shù)據(jù)讀寫詳解

P1 緩存 Buffer

1. 創(chuàng)建緩存

var buf = new Buffer(10);

var buf = new Buffer([10, 20, 30, 40, 50]);

//支持"ascii", "utf8", "utf16le", "ucs2", "base64" or "hex"
var buf = new Buffer("Simply Easy Learning", "utf-8");

2. 寫緩存 buf.write(string[, offset][, length][, encoding])

  • string:待寫入緩存的數(shù)據(jù)
  • offset:寫入緩存的偏移量
  • length:寫入數(shù)據(jù)的數(shù)量
  • encoding:編碼模式,默認為utf8
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");

console.log("Octets written : "+  len);
When the above program is executed, it produces the following result ?

Octets written : 20

3. 讀緩存 buf.toString([encoding][, start][, end])

  • encoding:編碼模式,默認為utf8
  • start:開始讀取的位置
  • end:結(jié)束讀取的位置
buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
  buf[i] = i + 97;
}
console.log( buf.toString('ascii'));       // outputs: abcdefghijklmnopqrstuvwxyz
console.log( buf.toString('ascii',0,5));   // outputs: abcde
console.log( buf.toString('utf8',0,5));    // outputs: abcde
console.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde

//運行輸出
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde

4. 轉(zhuǎn)換成JSON buf.toJSON()

  • encoding:編碼模式今穿,默認為utf8
  • start:開始讀取的位置
  • end:結(jié)束讀取的位置
var buf = new Buffer('Simply Easy Learning');
var json = buf.toJSON(buf);
console.log(json);

//運行輸出
[ 83, 105, 109, 112, 108, 121, 32, 69, 97, 115, 121, 32, 76, 101, 97, 114, 110, 105, 110,
   103 ]

5. 合并緩存 Buffer.concat(list[, totalLength])

  • list:緩存的數(shù)組
  • totalLength:合并緩沖的總長度
var buffer1 = new Buffer('TutorialsPoint ');
var buffer2 = new Buffer('Simply Easy Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);
console.log("buffer3 content: " + buffer3.toString());

//運行輸出
buffer3 content: TutorialsPoint Simply Easy Learning

6. 比較緩存 buf.compare(otherBuffer);

  • otherBuffer:待比較的緩存
var buffer1 = new Buffer('ABC');
var buffer2 = new Buffer('ABCD');
var result = buffer1.compare(buffer2);

if(result < 0) {
   console.log(buffer1 +" comes before " + buffer2);
}else if(result == 0){
   console.log(buffer1 +" is same as " + buffer2);
}else {
   console.log(buffer1 +" comes after " + buffer2);
}

//運行輸出
ABC comes before ABCD

7. 拷貝緩存 buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])

  • targetBuffer:目標緩存
  • targetStart:目標的起始位置
  • sourceStart: 源的起始位置
  • sourceEnd:源的結(jié)束位置
var buffer1 = new Buffer('ABC');

//copy a buffer
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());

//運行輸出
buffer2 content: ABC

8. 分割緩存 buf.slice([start][, end])

  • start:開始位置
  • end:結(jié)束位置
var buffer1 = new Buffer('TutorialsPoint');
//slicing a buffer
var buffer2 = buffer1.slice(0,9);
console.log("buffer2 content: " + buffer2.toString());));

//運行輸出
buffer2 content: Tutorials

9. 緩存長度 buf.length;

  • start:開始位置
  • end:結(jié)束位置
var buffer = new Buffer('TutorialsPoint');
//length of the buffer
console.log("buffer length: " + buffer.length);

//運行輸出
buffer length: 14

P2 文件系統(tǒng) FileSystem

1. 同步讀取 readFileSync

//沒有聲明encoding時返回二進制數(shù)據(jù)
var fs = require('fs');
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());

//聲明encoding時返回字符串
var fs = require('fs');
var data = fs.readFileSync('input.txt',  { encoding: 'utf-8' });
console.log("Synchronous read: " + data.toString());

//使用try..catch處理異常
try{
    var err = fs.readFileSync('noneExist.txt');
}catch(err){
    console.log(err.message);  // 輸出no such file or directory 'noneExist.txt'
}

2. 異步讀取 readFile

//沒有聲明encoding時返回二進制數(shù)據(jù)
fs.readFile('input.txt', function(err, data){
    if (err) {
      return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});

//聲明encoding時返回字符串
fs.readFile('input.txt', {encoding: 'utf-8'}, function(err, data){
    if (err) {
      return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});

3. 打開文件 fs.open(path, flags[, mode], callback)

Flag Description
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.
rs+ Open file for reading and writing, asking 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 the 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 the path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like 'a+' but fails if the the path exists.
// 異步打開文件
var fs = require("fs");
console.log("Going to open file!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
  console.log("File opened successfully!");     
});

4. 取文件信息 fs.stat(path, callback)

Method Description
stats.isFile() Returns true if file type of a simple file.
stats.isDirectory() Returns true if file type of a directory.
stats.isBlockDevice() Returns true if file type of a block device.
stats.isCharacterDevice() Returns true if file type of a character device.
stats.isSymbolicLink() Returns true if file type of a symbolic link.
stats.isFIFO() Returns true if file type of a FIFO.
stats.isSocket() Returns true if file type of asocket.
var fs = require("fs");
console.log("Going to get file info!");
fs.stat('input.txt', function (err, stats) {
   if (err) {
       return console.error(err);
   }
   console.log(stats);
   console.log("Got file info successfully!");

   // Check file type
   console.log("isFile ? " + stats.isFile());
   console.log("isDirectory ? " + stats.isDirectory());    
});

運行程序后輸出

Going to get file info!
{ 
   dev: 1792,
   mode: 33188,
   nlink: 1,
   uid: 48,
   gid: 48,
   rdev: 0,
   blksize: 4096,
   ino: 4318127,
   size: 97,
   blocks: 8,
   atime: Sun Mar 22 2015 13:40:00 GMT-0500 (CDT),
   mtime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT),
   ctime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT) 
}
Got file info successfully!
isFile ? true
isDirectory ? false

5. 寫文件 fs.writeFile(filename, data[, options], callback)

  • path:文件名稱(包括路徑)
  • data:字符串(String)或者數(shù)據(jù)緩存(Buffer)
  • options:可選項婚肆,可以設置 encoding , mode, flag贯卦; 默認encoding是 utf8, mode是八進制 0666麸粮,flag是 w
  • callback:包括一個錯誤返回參數(shù)的回調(diào)函數(shù)
var fs = require("fs");

console.log("Going to write into existing file");
fs.writeFile('input.txt', 'Simply Easy Learning!',  function(err) {
   if (err) {
      return console.error(err);
   }
   
   console.log("Data written successfully!");
   console.log("Read newly written data");
   fs.readFile('input.txt', function (err, data) {
      if (err) {
         return console.error(err);
      }
      console.log("Asynchronous read: " + data.toString());
   });
});

//運行后輸出
Going to write into existing file
Data written successfully!
Read newly written data
Asynchronous read: Simply Easy Learning!

6. 讀文件 fs.read(fd, buffer, offset, length, position, callback)

  • fd:讀取成功后返回的文件句柄
  • buffer:讀取后的數(shù)據(jù)會寫入到該緩沖區(qū)
  • offset:寫入緩沖區(qū)的偏移地址
  • length:讀取的數(shù)據(jù)數(shù)量
  • position:讀取的位置慧脱,如果為 null,則從當前位置讀取
  • callback:回調(diào)函數(shù)
var fs = require("fs");
var buf = new Buffer(1024);

console.log("Going to open an existing file");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("Going to read the file");
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }
      console.log(bytes + " bytes read");
      
      // Print only read bytes to avoid junk.
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
   });
});

//運行后輸出
Going to open an existing file
File opened successfully!
Going to read the file
97 bytes read
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

7. 關(guān)閉文件 fs.close(fd, callback)

  • fd:讀取成功后返回的文件句柄
  • callback:回調(diào)函數(shù)
var fs = require("fs");
var buf = new Buffer(1024);

console.log("Going to open an existing file");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("Going to read the file");
   
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }

      // Print only read bytes to avoid junk.
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }

      // Close the opened file.
      fs.close(fd, function(err){
         if (err){
            console.log(err);
         } 
         console.log("File closed successfully.");
      });
   });
});

//運行后輸出
Going to open an existing file
File opened successfully!
Going to read the file
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

File closed successfully.

8. 刪除文件 fs.unlink(path, callback)

  • path:文件名稱(包括路徑)
  • callback:回調(diào)函數(shù)
var fs = require("fs");

console.log("Going to delete an existing file");
fs.unlink('input.txt', function(err) {
   if (err) {
      return console.error(err);
   }
   console.log("File deleted successfully!");
});

9. 建立目錄 fs.mkdir(path[, mode], callback)

  • path:文件名稱(包括路徑)
  • mode:目錄權(quán)限丛晌,默認值 0777
  • callback:回調(diào)函數(shù)
var fs = require("fs");

console.log("Going to create directory /tmp/test");
fs.mkdir('/tmp/test',function(err){
   if (err) {
      return console.error(err);
   }
   console.log("Directory created successfully!");
});

10. 讀取目錄 fs.readdir(path, callback)

  • path:文件名稱(包括路徑)
  • callback:回調(diào)函數(shù)
var fs = require("fs");

console.log("Going to read directory /tmp");
fs.readdir("/tmp/",function(err, files){
   if (err) {
      return console.error(err);
   }
   files.forEach( function (file){
      console.log( file );
   });
});

11. 刪除目錄 fs.rmdir(path, callback)

  • path:文件名稱(包括路徑)
  • callback:回調(diào)函數(shù)
var fs = require("fs");

console.log("Going to delete directory /tmp/test");
fs.rmdir("/tmp/test",function(err){
   if (err) {
      return console.error(err);
   }
   console.log("Going to read directory /tmp");
   
   fs.readdir("/tmp/",function(err, files){
      if (err) {
         return console.error(err);
      }
      files.forEach( function (file){
         console.log( file );
      });
   });
});

P3 數(shù)據(jù)流 Streams

流是 unix 管道仅炊,可以從數(shù)據(jù)源讀取數(shù)據(jù),然后流向另一個目的地澎蛛。nodejs有4種數(shù)據(jù)流:

  • Readable:可讀流
  • Writable:可寫流 ? Stream which is used for write operation.
  • Duplex:讀寫流
  • Transform:轉(zhuǎn)換流抚垄,輸出數(shù)據(jù)根據(jù)輸入數(shù)據(jù)計算

1. 讀取流

假設有文本 input.txt,內(nèi)容如下:

Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

編寫main.js如下:

var fs = require("fs");
var data = '';

//readableStream.setEncoding('utf8'); 可以設置編碼谋逻,回調(diào)函數(shù)中的 chunk 就會是字符串

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Set the encoding to be utf8. 
readerStream.setEncoding('UTF8');

// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
   data += chunk;
});

readerStream.on('end',function(){
   console.log(data);
});

readerStream.on('error', function(err){
   console.log(err.stack);
});
console.log("Program Ended");

//運行輸出
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

2. 改寫流

var fs = require("fs");
var data = 'Simply Easy Learning';

// 創(chuàng)建可寫流
var writerStream = fs.createWriteStream('output.txt');

// 以utf8的編碼寫入數(shù)據(jù)
writerStream.write(data,'UTF8');

// 標記文件結(jié)束
// 當 end() 被調(diào)用時呆馁,所有數(shù)據(jù)會被寫入,然后流會觸發(fā)一個 finish 事件毁兆。
// 調(diào)用 end() 之后就不能再往可寫流中寫入數(shù)據(jù)
writerStream.end();

// 處理結(jié)束事件和錯誤事件
writerStream.on('finish', function() {
    console.log("Write completed.");
});

writerStream.on('error', function(err){
   console.log(err.stack);
});

console.log("Program Ended"); and easy way!!!!!

運行結(jié)束后output.txt的內(nèi)容為 Simply Easy Learning

3. 管道 Piping

管道是一個很棒的機制浙滤,你不需要自己管理流的狀態(tài)就可以從數(shù)據(jù)源中讀取數(shù)據(jù),然后寫入到目的地中气堕。

將input.txt的數(shù)據(jù)寫入到output.txt

var fs = require("fs");
var readerStream = fs.createReadStream('input.txt');
var writerStream = fs.createWriteStream('output.txt');
readerStream.pipe(writerStream);
console.log("Program Ended");

4. 管道 Chaining

鏈接可以將輸出流作為下一個函數(shù)的輸入

將壓縮文件input.txt.gz解壓后的內(nèi)容放到新文件output.txt

var fs = require('fs');
var zlib = require('zlib');

fs.createReadStream('input.txt.gz')
 .pipe(zlib.createGunzip())
 .pipe(fs.createWriteStream('output.txt'));

 console.log("File Compressed.");
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末纺腊,一起剝皮案震驚了整個濱河市畔咧,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌揖膜,老刑警劉巖誓沸,帶你破解...
    沈念sama閱讀 206,602評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異壹粟,居然都是意外死亡拜隧,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,442評論 2 382
  • 文/潘曉璐 我一進店門趁仙,熙熙樓的掌柜王于貴愁眉苦臉地迎上來洪添,“玉大人,你說我怎么就攤上這事幸撕∞弊椋” “怎么了?”我有些...
    開封第一講書人閱讀 152,878評論 0 344
  • 文/不壞的土叔 我叫張陵坐儿,是天一觀的道長。 經(jīng)常有香客問我宋光,道長貌矿,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,306評論 1 279
  • 正文 為了忘掉前任罪佳,我火速辦了婚禮逛漫,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘赘艳。我一直安慰自己酌毡,他們只是感情好,可當我...
    茶點故事閱讀 64,330評論 5 373
  • 文/花漫 我一把揭開白布蕾管。 她就那樣靜靜地躺著枷踏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪掰曾。 梳的紋絲不亂的頭發(fā)上旭蠕,一...
    開封第一講書人閱讀 49,071評論 1 285
  • 那天,我揣著相機與錄音旷坦,去河邊找鬼掏熬。 笑死,一個胖子當著我的面吹牛秒梅,可吹牛的內(nèi)容都是我干的旗芬。 我是一名探鬼主播,決...
    沈念sama閱讀 38,382評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼捆蜀,長吁一口氣:“原來是場噩夢啊……” “哼疮丛!你這毒婦竟也來了辆琅?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,006評論 0 259
  • 序言:老撾萬榮一對情侶失蹤这刷,失蹤者是張志新(化名)和其女友劉穎婉烟,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體暇屋,經(jīng)...
    沈念sama閱讀 43,512評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡似袁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,965評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了咐刨。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片昙衅。...
    茶點故事閱讀 38,094評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖定鸟,靈堂內(nèi)的尸體忽然破棺而出而涉,到底是詐尸還是另有隱情,我是刑警寧澤联予,帶...
    沈念sama閱讀 33,732評論 4 323
  • 正文 年R本政府宣布啼县,位于F島的核電站,受9級特大地震影響沸久,放射性物質(zhì)發(fā)生泄漏季眷。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,283評論 3 307
  • 文/蒙蒙 一卷胯、第九天 我趴在偏房一處隱蔽的房頂上張望子刮。 院中可真熱鬧,春花似錦窑睁、人聲如沸挺峡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,286評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽橱赠。三九已至,卻和暖如春裳朋,著一層夾襖步出監(jiān)牢的瞬間病线,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,512評論 1 262
  • 我被黑心中介騙來泰國打工鲤嫡, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留送挑,地道東北人。 一個月前我還...
    沈念sama閱讀 45,536評論 2 354
  • 正文 我出身青樓暖眼,卻偏偏與公主長得像惕耕,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子诫肠,可洞房花燭夜當晚...
    茶點故事閱讀 42,828評論 2 345

推薦閱讀更多精彩內(nèi)容

  • https://nodejs.org/api/documentation.html 工具模塊 Assert 測試 ...
    KeKeMars閱讀 6,305評論 0 6
  • 文件系統(tǒng)模塊是一個封裝了標準的 POSIX 文件 I/O 操作的集合司澎。通過require('fs')使用這個模塊欺缘。...
    保川閱讀 773評論 0 0
  • //公共引用 varfs =require('fs'), path =require('path'); 1、讀取文...
    才気莮孒閱讀 827評論 0 1
  • Node.js 常用工具 util 是一個Node.js 核心模塊挤安,提供常用函數(shù)的集合谚殊,用于彌補核心JavaScr...
    FTOLsXD閱讀 530評論 0 2
  • 本文的主要內(nèi)容是對nodejs提供的一些重要模塊,結(jié)合官方API進行介紹蛤铜,遇到精彩的文章嫩絮,我會附在文中并標明了出處...
    艾倫先生閱讀 938評論 0 3