Node.js檔案操作方法匯總,node.js操作方法

來源:互聯網
上載者:User

Node.js檔案操作方法匯總,node.js操作方法

Node.js和其他語言一樣,也有檔案操作。先不說node.js中的檔案操作,其他語言的檔案操作一般也都是有開啟、關閉、讀、寫、檔案資訊、建立刪除目錄、刪除檔案、檢測檔案路徑等。在node.js中也是一樣,也都是這些功能,可能就是api與其他語言不太一樣。

一、同步、非同步開啟關閉

/** * Created by Administrator on 2016/3/21. */var fs=require("fs");//同步讀 fs.openSync = function(path, flags, mode)//模組fs.js檔案中如上面定義的openSync 函數3個參數//.1.path 檔案路徑//2.flags 開啟檔案的模式//3.model 設定檔案訪問模式//fd檔案描述var fd=fs.openSync("data/openClose.txt",'w');//fs.closeSync = function(fd)fs.closeSync(fd);//非同步讀寫//fs.open = function(path, flags, mode, callback_)//fs.close = function(fd, callback)fs.open("data/openColse1.txt",'w',function(err,fd) {  if (!err)  {    fs.close(fd,function(){      console.log("closed");    });  }});

其中的flags其他語言也會有.其實主要分3部分 r、w、a.和C中的差不多。

1.r —— 以唯讀方式開啟檔案,資料流的初始位置在檔案開始
2.r+ —— 以可讀寫方式開啟檔案,資料流的初始位置在檔案開始
3.w ——如果檔案存在,則將檔案長度清0,即該檔案內容會丟失。如果不存在,則嘗試建立它。資料流的初始位置在檔案開始
4.w+ —— 以可讀寫方式開啟檔案,如果檔案不存在,則嘗試建立它,如果檔案存在,則將檔案長度清0,即該檔案內容會丟失。資料流的初始位置在檔案開始
5.a —— 以唯寫方式開啟檔案,如果檔案不存在,則嘗試建立它,資料流的初始位置在檔案末尾,隨後的每次寫操作都會將資料追加到檔案後面。
6.a+ ——以可讀寫方式開啟檔案,如果檔案不存在,則嘗試建立它,資料流的初始位置在檔案末尾,隨後的每次寫操作都會將資料追加到檔案後面。

二、讀寫

1.簡單檔案讀寫

/** * Created by Administrator on 2016/3/21. */var fs = require('fs');var config = {  maxFiles: 20,  maxConnections: 15,  rootPath: "/webroot"};var configTxt = JSON.stringify(config);var options = {encoding:'utf8', flag:'w'};//options 定義字串編碼 開啟檔案使用的模式 標誌的encoding、mode、flag屬性 可選//非同步//fs.writeFile = function(path, data, options, callback_)//同步//fs.writeFileSync = function(path, data, options)fs.writeFile('data/config.txt', configTxt, options, function(err){  if (err){    console.log("Config Write Failed.");  } else {    console.log("Config Saved.");    readFile();  }});function readFile(){  var fs = require('fs');  var options = {encoding:'utf8', flag:'r'};  //非同步  //fs.readFile = function(path, options, callback_)  //同步  //fs.readFileSync = function(path, options)  fs.readFile('data/config.txt', options, function(err, data){    if (err){      console.log("Failed to open Config File.");    } else {      console.log("Config Loaded.");      var config = JSON.parse(data);      console.log("Max Files: " + config.maxFiles);      console.log("Max Connections: " + config.maxConnections);      console.log("Root Path: " + config.rootPath);    }  });}
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe SimpleReadWrite.jsConfig Saved.Config Loaded.Max Files: 20Max Connections: 15Root Path: /webrootProcess finished with exit code 0

2.同步讀寫

/** * Created by Administrator on 2016/3/21. */var fs = require('fs');var veggieTray = ['carrots', 'celery', 'olives'];fd = fs.openSync('data/veggie.txt', 'w');while (veggieTray.length){  veggie = veggieTray.pop() + " ";  //系統api   //fd 檔案描述 第二個參數是被寫入的String或Buffer  // offset是第二個參數開始讀的索引 null是表示當前索引  //length 寫入的位元組數 null一直寫到資料緩衝區末尾  //position 指定在檔案中開始寫入的位置 null 檔案當前位置  // fs.writeSync(fd, buffer, offset, length[, position]);  // fs.writeSync(fd, string[, position[, encoding]]);  //fs.writeSync = function(fd, buffer, offset, length, position)  var bytes = fs.writeSync(fd, veggie, null, null);  console.log("Wrote %s %dbytes", veggie, bytes);}fs.closeSync(fd);var fs = require('fs');fd = fs.openSync('data/veggie.txt', 'r');var veggies = "";do {  var buf = new Buffer(5);  buf.fill();  //fs.readSync = function(fd, buffer, offset, length, position)  var bytes = fs.readSync(fd, buf, null, 5);  console.log("read %dbytes", bytes);  veggies += buf.toString();} while (bytes > 0);fs.closeSync(fd);console.log("Veggies: " + veggies);
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe syncReadWrite.jsWrote olives 7bytesWrote celery 7bytesWrote carrots 8bytesread 5bytesread 5bytesread 5bytesread 5bytesread 2bytesread 0bytesVeggies: olives celery carrots     Process finished with exit code 0

3.非同步讀寫 和同步讀寫的參數差不多就是多了callback

/** * Created by Administrator on 2016/3/21. */var fs = require('fs');var fruitBowl = ['apple', 'orange', 'banana', 'grapes'];function writeFruit(fd){  if (fruitBowl.length){    var fruit = fruitBowl.pop() + " ";   // fs.write(fd, buffer, offset, length[, position], callback);   // fs.write(fd, string[, position[, encoding]], callback);   // fs.write = function(fd, buffer, offset, length, position, callback)    fs.write(fd, fruit, null, null, function(err, bytes){      if (err){        console.log("File Write Failed.");      } else {        console.log("Wrote: %s %dbytes", fruit, bytes);        writeFruit(fd);      }    });  } else {    fs.close(fd);    ayncRead();  }}fs.open('data/fruit.txt', 'w', function(err, fd){  writeFruit(fd);});function ayncRead(){  var fs = require('fs');  function readFruit(fd, fruits){    var buf = new Buffer(5);    buf.fill();    //fs.read = function(fd, buffer, offset, length, position, callback)    fs.read(fd, buf, 0, 5, null, function(err, bytes, data){      if ( bytes > 0) {        console.log("read %dbytes", bytes);        fruits += data;        readFruit(fd, fruits);      } else {        fs.close(fd);        console.log ("Fruits: %s", fruits);      }    });  }  fs.open('data/fruit.txt', 'r', function(err, fd){    readFruit(fd, "");  });}
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe asyncReadWrite.jsWrote: grapes 7bytesWrote: banana 7bytesWrote: orange 7bytesWrote: apple 6bytesread 5bytesread 5bytesread 5bytesread 5bytesread 5bytesread 2bytesFruits: grapes banana orange apple  Process finished with exit code 0

4.流式讀寫

/** * Created by Administrator on 2016/3/21. */var fs = require('fs');var grains = ['wheat', 'rice', 'oats'];var options = { encoding: 'utf8', flag: 'w' };//從下面的系統api可以看到 createWriteStream 就是建立了一個writable流//fs.createWriteStream = function(path, options) {//  return new WriteStream(path, options);//};////util.inherits(WriteStream, Writable);//fs.WriteStream = WriteStream;//function WriteStream(path, options)var fileWriteStream = fs.createWriteStream("data/grains.txt", options);fileWriteStream.on("close", function(){  console.log("File Closed.");  //流式讀  streamRead();});while (grains.length){  var data = grains.pop() + " ";  fileWriteStream.write(data);  console.log("Wrote: %s", data);}fileWriteStream.end();//流式讀function streamRead(){  var fs = require('fs');  var options = { encoding: 'utf8', flag: 'r' };  //fs.createReadStream = function(path, options) {  //  return new ReadStream(path, options);  //};  //  //util.inherits(ReadStream, Readable);  //fs.ReadStream = ReadStream;  //  //function ReadStream(path, options)  //createReadStream 就是建立了一個readable流  var fileReadStream = fs.createReadStream("data/grains.txt", options);  fileReadStream.on('data', function(chunk) {    console.log('Grains: %s', chunk);    console.log('Read %d bytes of data.', chunk.length);  });  fileReadStream.on("close", function(){    console.log("File Closed.");  });}
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe StreamReadWrite.jsWrote: oats Wrote: rice Wrote: wheat File Closed.Grains: oats rice wheat Read 16 bytes of data.File Closed.Process finished with exit code 0

 個人覺得像這些api用一用感受一下就ok了,遇到了會用就行了。

您可能感興趣的文章:
  • nodejs檔案操作模組FS(File System)常用函數簡明總結
  • Node.js檔案操作詳解
  • Node.js本地檔案操作之檔案拷貝與目錄遍曆的方法
  • Node.js程式中的本地檔案操作用法小結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.