Created
March 26, 2021 00:22
-
-
Save javascripto/5b627d18c713ef485a730c8b8d850eb5 to your computer and use it in GitHub Desktop.
Node Read Write File Buffer vs Streams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const fs = require('fs') | |
| const imageSource = `${__dirname}/image.png`; | |
| const imageTarget = `${__dirname}/image.copy.png`; | |
| function copiaUsandoBufferInteiroDoArquivoEmMemoria() { | |
| fs.readFile(imageSource, (error, buffer) => { | |
| if (error) return console.log('erro ao ler arquivo'); | |
| console.log(buffer); | |
| console.log('Arquivo lido com sucesso'); | |
| fs.writeFile(imageTarget, buffer, (error) => { | |
| if (error) return console.log('erro ao escrever arquivo'); | |
| console.log('Arquivo copiado com sucesso!'); | |
| }); | |
| }); | |
| } | |
| function copiaComStreamsUsandoPartesDeBufferParalelamente() { | |
| fs.createReadStream(imageSource) | |
| .on('data', chunk => console.log(`Lendo ${chunk.length} bytes do arquivo`)) | |
| .pipe(fs.createWriteStream(imageTarget)) | |
| .on('finish', () => console.log('Arquivo copiado com sucesso')) | |
| } | |
| console.clear(); | |
| // copiaUsandoBufferInteiroDoArquivoEmMemoria(); | |
| // copiaComStreamsUsandoPartesDeBufferParalelamente(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment