由于node.js是服務(wù)端的程序,必須要有讀寫文件操作,在原生的js中沒(méi)有這樣的功能,在Node中如果要讀寫文件,必須使用文件系統(tǒng)模塊(fs)提供了文件操作的所有功能,js在瀏覽器端是不能進(jìn)行I/O操作的,是為了保護(hù)客戶端的安全,node內(nèi)置的js模塊,讓js能夠在node環(huán)境執(zhí)行的過(guò)程中,去操作服務(wù)器上的資源文件。
1、讀取文件內(nèi)容
讀取文件內(nèi)容有兩種方式:
- 1、將硬盤中的內(nèi)容全部讀取完后觸發(fā)回調(diào)。
- 2、從硬盤中讀取一節(jié)就觸發(fā)一次回調(diào),分段式去處理數(shù)據(jù)。
1.1、異步讀取文件
如果有錯(cuò)誤, error會(huì)是一個(gè)錯(cuò)誤對(duì)象,data是一個(gè)undefined,如果沒(méi)有錯(cuò)誤,error是一個(gè)null,data是讀取成功后的數(shù)據(jù)。
// 新建data.txt文件
this is a message!
// index.js文件
const fs = require('fs');
// 1.異步讀取文件
fs.readFile('./data.txt','utf-8', function(error, data) {
// 如果有錯(cuò)誤, error會(huì)是一個(gè)錯(cuò)誤對(duì)象,data是一個(gè)undefined
// 如果沒(méi)有錯(cuò)誤,error是一個(gè)null,data是讀取成功后的數(shù)據(jù)
if(error) return;
console.log(data.toString()); // this is a message!
})
接下來(lái),嘗試讀取服務(wù)器上的文件內(nèi)容
首先在目錄下創(chuàng)建靜態(tài)資源首頁(yè)index.html和配置項(xiàng)頁(yè)面setting.html頁(yè)面
// public文件下的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>首頁(yè)</title>
</head>
<body>
<p>首頁(yè)</p>
</body>
</html>
// public文件下的setting.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>配置頁(yè)</title>
</head>
<body>
<p>配置項(xiàng)頁(yè)面</p>
</body>
</html>
接下來(lái)開(kāi)始server服務(wù)文件的創(chuàng)建
// server.js
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html;charset=utf8');
if(req.url == '/') {
fs.readFile('./public/index.html', 'utf-8', function(error, data) {
if(error) return;
console.log(data.toString())
res.end(data)
})
} else if(req.url == '/setting') {
fs.readFile('./public/setting.html', 'utf-8', function(error, data) {
if(error) return;
console.log(data.toString())
res.end(data)
})
}
}).listen(3000, () => console.log('Server start at 3000 port....'))
上述代碼會(huì)在打開(kāi)本地3000端口后,讀取到index.html服務(wù)器上的內(nèi)容。

可以看到,文件是成功讀取到了
1.2、同步讀取文件
同步與異步的區(qū)別在于,異步執(zhí)行到readFile函數(shù)后會(huì)接著執(zhí)行下面的代碼,回調(diào)函數(shù)的執(zhí)行不會(huì)阻塞程序,而同步的方式讀取,如果文件內(nèi)容十分龐大,那么會(huì)直接導(dǎo)致程序阻塞。
// 同步讀取文件的方式
// 同步讀取文件
console.time('time2');
const data = fs.readFileSync('./data.txt');
console.timeEnd('time2');
console.log(data.toString());
同步讀取文件時(shí),如果讀取文件錯(cuò)誤,那么會(huì)直接導(dǎo)致程序的崩潰,而異步則可以通過(guò)error參數(shù)進(jìn)行捕獲。因此,同步獲取文件需要捕獲異常的話需要手動(dòng)進(jìn)行捕獲。
// 同步獲取文件捕獲異常
try {
console.time('time2');
const data = fs.readFileSync('./data.pdf');
console.timeEnd('time2');
console.log(data.toString());
} catch(error) {
console.log('未讀取到文件....')
}

2、文件內(nèi)容寫入
2.1、異步文件數(shù)據(jù)寫入
fs.writeFile('文件名', '數(shù)據(jù)', function(error) {
// 數(shù)據(jù)寫入失敗時(shí)的回調(diào)函數(shù)
})
在index.js中測(cè)試寫入數(shù)據(jù)到test.txt中去,需要注意的是:如果txt中是存在數(shù)據(jù)的,那么再次寫入會(huì)直接全部覆蓋之前的數(shù)據(jù),如果內(nèi)容為空,則直接寫入。
const txtContent =
`人民有信仰,國(guó)家才有力量。將社會(huì)主義核心價(jià)值觀的教育宣傳活動(dòng),融入國(guó)民教育和精神文明建設(shè)全過(guò)程,同改革開(kāi)放的實(shí)踐經(jīng)驗(yàn)和偉大成就聯(lián)系起來(lái),同全面建成小康社會(huì)的奮斗目標(biāo)聯(lián)系起來(lái),我們就能不斷形成更加廣泛的價(jià)值認(rèn)同,不僅為國(guó)家發(fā)展助力,更為民族進(jìn)步鑄魂。`
fs.writeFile('test.txt', txtContent, 'utf-8', function(error) {
if(error) {
console.log('文件寫入數(shù)據(jù)失敗...');
return;
}
console.log('文件寫入數(shù)據(jù)成功...')
})

2.2、同步的文件寫入
const syncContent = `<span>this is a message!</span>`;
try {
fs.writeFileSync('write.txt', syncContent);
console.log('文件寫入成功...')
} catch(error) {
console.log('文件寫入錯(cuò)誤...')
}
2.3、追加寫入的內(nèi)容
異步追加寫入的內(nèi)容
fs.appendFile(文件路徑, 數(shù)據(jù), 回調(diào)函數(shù));
const syncContent = `<span>this is a message!</span>`;
try {
fs.writeFileSync('write.txt', syncContent);
console.log('文件寫入成功...')
} catch(error) {
console.log('文件寫入錯(cuò)誤...')
}
const data = `\n<div>this is a box!<div>`
fs.appendFile('./write.txt',data, function(error) {
if(error) {
console.log('數(shù)據(jù)寫入失敗...');
return;
}
console.log('數(shù)據(jù)寫入成功...')
})

數(shù)據(jù)成功的追加進(jìn)去write.txt文件中。