作者: 黄杰;
标签: fs模块
文件系统(File System)
基本概念
- 服务器的本质就是将本地的文件发送给远程客户端
- 学习fs模块的API
- 使用fs模块前,需要引入 cost fs = require('fs');
特点
- 提供同步异步两种选择
- 同步导致阻塞
- 异步操作完成通过回调返回结果
使用
同步写入操作
let fs = require("fs");
//同步打开文件
let fd = fs.openSync('text_1', 'w');
console.log(fd)
//写入内容
fs.writeFileSync(fd, 'hello ink!');
//退出
fs.closeSync(fd);
异步写入操作
let fs = require("fs");
fs.open("text_2.txt", "w", (err, fd) => {
if( !err ) {
fs.writeFile(fd, 'ink nice to meet u!!', (err) => {
if( !err ) {
console.log('success');
fs.close(fd, (err) => {
if ( !err ) {
console.log('file closed');
} else {
throw err;
}
})
} else {
throw err;
}
});
} else {
throw err;
}
})
文件流写入操作
let fs = require("fs");
let ws = fs.createWriteStream('text_3.txt');
//打开通道
ws.once('open', () => {
console.log('通道已打开!')
})
ws.write("what's your name?\n");
ws.write("what's your name?\n");
ws.write("what's your name?\n");
ws.write("what's your name?\n");
ws.end();
//监听通道关闭
ws.once('close', () => {
console.log('通道已关闭!')
})
文件读取操作
读取图片并写入到另一个文件中(单个文件操作)
let fs = require("fs");
fs.readFile("../images/deskPic1.jpg", (err, data) => {
if ( !err ) {
console.log(data);
//写入图片文件
fs.writeFile('receiveimage_1.jpg', data, (err, data) => {
if ( !err ) {
console.log('transfer success!');
} else {
throw err;
}
})
} else {
throw err;
}
})
使用文件读入流处理
let fs = require("fs");
let readStream = fs.createReadStream("../images/deskPic2.jpg");
let writeStream = fs.createWriteStream("receiveimage_2.jpg");
//监听文件流打开关闭
readStream.once('open', () => {
console.log('readstream opened');
})
readStream.once('clos', () => {
console.log('readstream closed');
})
writeStream.once('open', () => {
console.log('writeStream opened');
})
writeStream.once('clos', () => {
console.log('writeStream closed');
})
//读入流操作
readStream.on('data', (data) => {
console.log(data);
//文件过大时分段读取
//写入
writeStream.write(data);
})
简便方法
let fs = require("fs");
let readStream = fs.createReadStream("../images/deskPic2.jpg");
let writeStream = fs.createWriteStream("receiveimage_2.jpg");
//创建管道
readStream.pipe(writeStream);