File System是Nodejs中用来操做文件的库,能够经过const fs = require('fs')引用。html
经常使用的方法有异步文件读取fs.readFile、异步文件写入fs.writeFile、同步文件读取fs.readFileSync、同步文件写入fs.writeFileSync。因为同步操做可能会形成阻塞,一般建议使用异步操做避免该问题。node
示例代码:/lesson03/server.jsgit
nodejs.org/dist/latest…github
fs.writeFile可向文件写入信息,若文件不存在会自动建立。api
fs.writeFile('./test.txt', 'test', (error) => {
if (error) {
console.log('文件写入失败', error)
} else {
console.log('文件写入成功')
}
})
复制代码
fs.writeFile的主要参数:浏览器
第一个参数为写入的文件路径bash
第二个参数为写入内容(可为<string> | <Buffer> | <TypedArray> | <DataView>)less
第三个参数为回调函数,传入数据为error对象,其为null时表示成功。异步
示例代码:/lesson03/server.js函数
fs.readFile用来读取文件。
fs.readFile('./test.txt', (error, data) => {
if (error) {
console.log('文件读取失败', error)
} else {
// 此处因肯定读取到的数据是字符串,能够直接用toString方法将Buffer转为字符串。
// 如果须要传输给浏览器能够直接用Buffer,机器之间通讯是直接用Buffer数据。
console.log('文件读取成功', data.toString())
}
})
复制代码
fs.readFile主要参数:
第一个参数为读取的文件路径
第二个参数为回调函数。回调函数传入第一个参数为error对象,其为null时表示成功,第二个为数据,可为<string> | <Buffer>。