基础写入文件
const fs = require('fs');
// 打开文件; 如果是fs.openSync('hello.txt', 'r');只读,那么要先手动创建hello.txt,不然会报错
const fd = fs.openSync('hello.txt', 'w');
// 写入内容
fs.writeSync(fd, '这些内容会写入');
// 关闭
fs.closeSync(fd)
简单写入文件
const fs = require('fs');
fs.writeFileSync('hello.txt', '写入的内容')
流式文件写入
const fs = require('fs');
const wr = fs.createWriteStream('hello.txt');
wr.once('open', () => console.log('open'))
wr.once('close', () => console.log('close'))
wr.write('1111\n')
wr.write('2222\n')
wr.write('3333\n')
// 关闭 wr.close(); 会写入wr.write('1111\n');就直接关闭 ;wr.end()会等全部写完关闭
wr.end();
简单文件读取
const fs = require('fs');
const result = fs.readFileSync('hello.txt', 'utf-8');
console.log(result)
流式文件读取
const fs = require('fs');
const rs = fs.createReadStream('hello.txt')
rs.once('open', () => console.log('open'))
rs.once('close', () => console.log('close'))
rs.on('data', data => {
console.log(data.toString())
})
流式文件拷贝(读取 + 写入)
const fs = require('fs');
const rs = fs.createReadStream('a.pdf')
const wr = fs.createWriteStream('copy2.pdf')
rs.once('open', () => console.log('open'))
rs.once('close', () => {
wr.end()
console.log('close')
})
wr.once('close', () => console.log('write close'))
// rs.pipe(wr) // 这行代码等同于下面
rs.on('data', data => {
wr.write(data);
})
// 等同于上面
fs.copyFileSync('a.pdf', 'b.pdf')
复制文件
- fs.js
const fs = require('fs');
var args = process.argv
const rs = fs.createReadStream(args[2])
const wr = fs.createWriteStream(args[3])
rs.pipe(wr)
-
命令行中输入
ab082e322e6495422177bb9e17333f2.png
node fs a.pdf b.pdf
其他fs
const fs = require('fs');
// 检查文件是否存在
console.log(fs.existsSync('a.pdf'))
// 查询文件状态(信息)
fs.stat('a.pdf', (err, stat) => {
// stat 对象详细信息,见 fs.Stats
if (err) {
console.log(err)
} else {
console.log(stat.isFile(), stat.isDirectory(), stat.size)
}
})
网友评论