前言
- fs 是file system的簡寫俗壹, 就是文件系統(tǒng)的意思
- 在Node中的javascript 具有文件操作能力,但沒有Dom和Bom的概念
- 在fs 這個(gè)系統(tǒng)模塊中妙同,就提供了所有關(guān)于文件操作的API, 例如:fs.readFile就是用來讀取文件的
使用
一. 加載fs模塊
const fs = require(fs);
二. 讀取文件數(shù)據(jù)(fs.readFile)
接收2個(gè)參數(shù) fs.readFile(path, callback(error, data))
- path坝咐,第一個(gè)參數(shù)是要讀取的文件路徑
- callback唧垦,第二個(gè)參數(shù)是回調(diào)函數(shù)懂拾,回調(diào)函數(shù)接收2個(gè)參數(shù)
- error, 錯(cuò)誤對象, 當(dāng)讀取成功時(shí)值為
null
- data, 讀取到的文件數(shù)據(jù), 當(dāng)取失敗時(shí)值為
undefined
- error, 錯(cuò)誤對象, 當(dāng)讀取成功時(shí)值為
//當(dāng)前目錄下有個(gè)hello.txt的文件煤禽, 內(nèi)容是’hello'
fs.readFile('./hello.txt', (error, data) => {
console.log(data) //讀取成功,返回16進(jìn)制的數(shù)據(jù) <Buffer 68 65 6c 6c 6f>
})
三. toString()
將16進(jìn)制數(shù)據(jù)轉(zhuǎn)換為人類能認(rèn)識(shí)的數(shù)據(jù)
//當(dāng)前目錄下有個(gè)hello.txt的文件委粉, 內(nèi)容是’hello'
fs.readFile('./hello.txt', (error, data) => {
console.log(data) //讀取成功呜师,返回16進(jìn)制的數(shù)據(jù) <Buffer 68 65 6c 6c 6f>
console.log(data.toString()); // hello
})