Node.js_文件系统 FS

文件系统 FS——File Systemnode

所谓的文件系统,就是对计算机中的文件进行增、删、查、改等操做json

是一个服务器的基础服务器

node 经过核心 FS 模块来操做文件系统ui

  • 简单写

// 1. 导入 fs 模块spa

  • const fs = require('fs');

// 2. 简单写入文件code

  • fs.writeFile('./hello.txt', 'Hello File System!', { encoding:'utf-8', mode: 0o666, // 4 2 0 可读 可写 flag: 'a' // 追加写操做  }, err=>{ // 3. 判断方法是否出错 if(err){ // 若是出错 err 为一个对象  console.log(err); }else{ console.log('文件写入成功'); }; } );
  • 流式写(能够一点一点写入内容)

// 1. 导入 fs 模块对象

  • const fs = require('fs');

// 2. 建立可写流blog

  • const ws = fs.createWriteStream('./test.txt'); // 绑定监听事件,监听 可写流 有没有开始工做 ws.on('open', ()=>{ console.log('开始写了!'); }); // 绑定监听事件,监听 可写流 有没有开始工做 ws.on('close', ()=>{ console.log('写完了!'); }); // ws.close(); 会当即关闭 写入流,即便 文件流 内容尚未彻底写入文件 // ws.end(); // 等待 写入流 内容所有写入文件,再关闭

// 3. 往 可写流 写入内容事件

  • ws.write('丫丫啦个呸的... ...'); ws.write('啥玩意儿?!');

// 4. 关闭写入流ip

  • ws.end();
  • 简单读

// 1. 导入 fs 模块

  • const fs = require('fs');

// 2. 读文件

  • fs.readFile( './package.json', (err, bufData)=>{ if(err){ console.log(err); }else{ console.log(bufData.toString()); }; } );
  • 流式读(能够一点一点读)

// 1. 导入 fs 模块

  • const fs = require('fs');

// 2. 建立可读流

  • const rs = fs.createReadStream('D:\\Audiio\\test.mp4'); // 绑定监听事件 rs.on('open', ()=>console.log('开始读!')); rs.on('close', ()=>console.log('开始读!')); // 绑定读取文件事件 rs.on('data', bufData=>{ console.log('开始读!'); });
  • 文件复制
  • const {createReadStream, createWriteStream} = require('fs'); const ws = createWriteStream('./testCopy.mp4'); // 绑定监听事件,监听 可写流 有没有开始工做 ws.once('open', ()=>{ console.log('开始写了!'); }); // 绑定监听事件,监听 可写流 有没有开始工做 ws.once('close', ()=>{ console.log('写完了!'); }); const rs = createReadStream('D:\\Audiio\\test.mp4'); // 绑定监听事件 rs.once('open', ()=>console.log('开始读!')); rs.once('close', ()=>{ console.log('读完了!'); ws.end(); // 等待 写入流 内容所有写入文件,再关闭 }); // 绑定读取文件事件 rs.on('data', bufData=>{ console.log('读ing'); ws.write(bufData); });
  • 管道 读写 数据流
  • const {createReadStream, createWriteStream} = require('fs'); const ws = createWriteStream('./testCopy.mp4'); const rs = createReadStream('D:\\Audiio\\test.mp4'); rs.pipe(ws);

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

5

相关文章
相关标签/搜索