MENU

nodejs学习笔记3

July 27, 2020 • Read: 202 • Node.js

文件流写入

var fs = require('fs');
var data = 'kono dio da!';

var ws = fs.createWriteStream('output.txt', { flags: 'w', encoding: 'utf8' });

ws.on('open', () => {
    console.log("开始写入");
});

ws.on('close', () => {
    console.log('closed');
});


ws.write(data);
ws.end(() => {
    console.log("写入完成");
});

文件流读取

/*
 * @Author: Mr.Sen
 * @LastEditTime: 2020-07-27 23:34:11
 * @Website: https://grimoire.cn
 * @Mr.Sen All rights reserved
 */ 
var fs = require('fs');

var path = './output.txt';
var rs = fs.createReadStream(path, {flags: 'r', encoding:'utf8'});

rs.on('open', () => {
    console.log('开始传输');
});

rs.on('data', (chunk) => {
    console.log('一批数据传输完成');
    console.log(chunk);
});

rs.on('close', () => {
    console.log('数据全部传输完成');
});

读取文件并写入

/*
 * @Author: Mr.Sen
 * @LastEditTime: 2020-07-27 23:44:52
 * @Website: https://grimoire.cn
 * @Mr.Sen All rights reserved
 */ 
var fs = require('fs');

var path = './file.zip';
// var rs = fs.createReadStream(path, {flags: 'r', encoding:'utf8'});
var rs = fs.createReadStream(path);
var ws = fs.createWriteStream('./a.zip');

rs.on('open', () => {
    console.log('开始传输');
});

rs.on('data', (chunk) => {
    console.log('一批数据传输完成');
    console.log(chunk);
    ws.write(chunk, ()=>{console.log('单批数据传输完成')});
});

rs.on('close', () => {
    ws.end()
    console.log('数据全部传输完成');
});

又或者……

/*
 * @Author: Mr.Sen
 * @LastEditTime: 2020-07-27 23:47:59
 * @Website: https://grimoire.cn
 * @Mr.Sen All rights reserved
 */ 
var fs = require('fs');

var path = './file.zip';
// var rs = fs.createReadStream(path, {flags: 'r', encoding:'utf8'});
var rs = fs.createReadStream(path);
var ws = fs.createWriteStream('./b.zip');

rs.on('open', () => {
    console.log('开始传输');
});

rs.on('data', (chunk) => {
    console.log('一批数据传输完成');
    console.log(chunk);
    // ws.write(chunk, ()=>{console.log('单批数据传输完成')});
});

rs.on('close', () => {
    // ws.end()
    console.log('数据全部传输完成');
});

rs.pipe(ws);
Archives Tip
QR Code for this page
Tipping QR Code