簡單的nodejs 檔案系統(fs)讀寫例子。

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   使用   sp   檔案   

在nodejs中,可以通過fs(file system)模組進行檔案的I/O操作。

API連結地址:

http://nodeapi.ucdok.com/#/api/fs.html

下面進行fs檔案系統的使用執行個體:

1、模組調用聲明:

var fs= require(‘fs‘);


  var path = require(‘path‘);

fs為檔案模組,path為系統路徑模組。

2、可以使用writeFile方法,將資料寫入檔案到某個檔案夾下。

fs.writeFile(filename, data, [options], callback)

filename為具體的檔案儲存路徑地址,

data為具體要寫入檔案的資料對象,

[options]為具體的儲存檔案配置,編碼格式等,

callback為具體的回呼函數,進行相應的錯誤捕捉及提示。

代碼如下:

fs.writeFile(path.join(__dirname, ‘account.js‘), JSON.stringify(tempAccount), function (err) {        if (err) throw err;        console.log("Export Account Success!");    });

以JSON格式將資料寫入到檔案路徑下。

3、使用readFile方法,進行檔案資料的讀取。

fs.readFile(filename, [options], callback)

filename為檔案路徑及名稱,

[options]為具體選項配置,包括資料的編碼方式,

callback為回呼函數,進行相應的錯誤處理及提示。

代碼如下:

fs.readFile(path.join(__dirname, ‘account.js‘), function (err,bytesRead) {    if (err) throw err;    console.log(bytesRead);});

結果為:

讀出資料二進位的流檔案,如果需要為具體的資料,需要進行編碼的配置,代碼如下:

fs.readFile(path.join(__dirname, ‘account.js‘),{encoding:‘utf-8‘}, function (err,bytesRead) {    if (err) throw err;    var data=JSON.parse(bytesRead);    console.log(data[0]);    console.log("readFile success");});

結果為:

4、讀取檔案夾下的相關ingwenj名稱。

readdir(path,callback)

path為具體讀取的檔案夾路徑地址,

callback為回呼函數。

readdirSync(path)為讀取檔案的即時同步版本方法。

path為具體的檔案夾路徑地址。

代碼如下:

var  data=fs.readdirSync(__dirname);console.log(data);

結果如下:

如此就實現了簡單的檔案寫入及讀取的執行個體,具體深入的應用還需進一步的學習。

如有錯誤,敬請讀者原諒。

 

簡單的nodejs 檔案系統(fs)讀寫例子。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.