let fs = require('fs')
let fsPath = '7901.txt';
let fd = fs.openSync(fsPath, 'w');
// fd 为文件的id 作为文件的唯一标识
console.log(fd);
let str = "shdfhsjfh"
fs.writeFileSync(fd, str)
fs.closeSync(fd)
let fs = require('fs')
let fsPath = "test.txt"
const xxx = "888"
fs.open(fsPath, 'w', (err, fd) => {
if (!err) {
fs.writeFile(fd, xxx, (err) => {
if (!err) {
console.log("写入成功");
fs.close(fd, (err) => {
if (!err) {
console.log("关闭成功");
} else {
throw err;
}
})
} else {
throw err;
}
})
} else {
throw err;
}
})
// 文件写入
let fs = require('fs')
// 创建文件流
let wsPath = 'wspath.txt'
let ws = fs.createWriteStream(wsPath)
ws.once('open', () => {
console.log("通道打开");
ws.write("11111111");
ws.write("222222222");
ws.write("3333333333");
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);