在nodejs中,可以通過(guò)fs(file system)模塊進(jìn)行文件的I/O操作。
API鏈接地址:
http://nodeapi.ucdok.com/#/api/fs.html
下面進(jìn)行fs文件系統(tǒng)的使用實(shí)例:
1、模塊調(diào)用聲明:
var fs= require('fs');var path = require('path');
fs為文件模塊,path為系統(tǒng)路徑模塊。
2、可以使用writeFile方法,將數(shù)據(jù)寫入文件到某個(gè)文件夾下。
fs.writeFile(filename, data, [options], callback)
filename為具體的文件保存路徑地址,
data為具體要寫入文件的數(shù)據(jù)對(duì)象,
[options]為具體的保存文件配置,編碼格式等,
callback為具體的回調(diào)函數(shù),進(jìn)行相應(yīng)的錯(cuò)誤捕捉及提示。
代碼如下:
fs.writeFile(path.join(__dirname, 'account.js'), JSON.stringify(tempAccount), function (err) { if (err) throw err; console.log("Export Account Success!"); });以JSON格式將數(shù)據(jù)寫入到文件路徑下。
3、使用readFile方法,進(jìn)行文件數(shù)據(jù)的讀取。
fs.readFile(filename, [options], callback)
filename為文件路徑及名稱,
[options]為具體選項(xiàng)配置,包括數(shù)據(jù)的編碼方式,
callback為回調(diào)函數(shù),進(jìn)行相應(yīng)的錯(cuò)誤處理及提示。
代碼如下:
fs.readFile(path.join(__dirname, 'account.js'), function (err,bytesRead) { if (err) throw err; console.log(bytesRead);});結(jié)果為:

讀出數(shù)據(jù)二進(jìn)制的流文件,如果需要為具體的數(shù)據(jù),需要進(jìn)行編碼的配置,代碼如下:
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");});結(jié)果為:

4、讀取文件夾下的相關(guān)ingwenj名稱。
readdir(path,callback)
path為具體讀取的文件夾路徑地址,
callback為回調(diào)函數(shù)。
readdirSync(path)為讀取文件的實(shí)時(shí)同步版本方法。
path為具體的文件夾路徑地址。
代碼如下:
var data=fs.readdirSync(__dirname);console.log(data);
結(jié)果如下:

如此就實(shí)現(xiàn)了簡(jiǎn)單的文件寫入及讀取的實(shí)例,具體深入的應(yīng)用還需進(jìn)一步的學(xué)習(xí)。
如有錯(cuò)誤,敬請(qǐng)讀者原諒。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注