Skip to content

Instantly share code, notes, and snippets.

@kenriortega
Created May 7, 2021 23:34
Show Gist options
  • Save kenriortega/5e7a53990f18fd5856d1b29d6b9ec5a9 to your computer and use it in GitHub Desktop.
Save kenriortega/5e7a53990f18fd5856d1b29d6b9ec5a9 to your computer and use it in GitHub Desktop.
Node.js Basic Stream data

Clase de stream nodejs API

'use strict'

const fs = require('fs')
const zlib = require('zlib')
const http = require('http')

Ejemplo para leer datos de un stream

// 1
const stream = fs.createReadStream('./package.json')
stream.setEncoding('utf8')
let pkg = ''
stream.on('data', (chunk) => {
    pkg += chunk
})
stream.on('end', () => console.log(pkg))

// 2
async function readFile() {
    const stream = fs.createReadStream('./package.json')
    stream.setEncoding('utf8')
    let pkg = ''

    for await (const chunk of stream) {
        pkg += chunk
    }
    return pkg
}

readFile().then(file => console.log(file))
// 3
const stream = fs.createReadStream('./package.json')
stream.setEncoding('utf8')
stream.pipe(process.stdout)

Ejemplos para usar createReadStream y createWriteStream para manejar los datos de un stream desde una fuente hacia una salida

// 1
const src = fs.createReadStream('./package.json')
const dst = fs.createWriteStream('./package-Copy.json')
src.setEncoding('utf8')
src.pipe(dst)

// 2
const src = fs.createReadStream('./package.json')
const dst = fs.createWriteStream('./package-Copy.json.gz')
const gzip = zlib.createGzip()
src.setEncoding('utf8')
src
  .pipe(gzip)
  .pipe(dst)

// 3
const server = http.createServer((req, res) => {
    req.pipe(res)
})
server
    .listen(8080, () => console.log(`Server runing om port 8080`))

const dst = fs.createWriteStream("./stdin.txt")
process.stdin.pipe(dst)

Ejemplo para salvar los datos provenientes de skimdb.npmjs.com

'use strict'

const { Client } = require('undici')
const client = new Client(`https://skimdb.npmjs.com`)
const fs = require('fs')
const options = {
    path:'/registry/_changes',
    method: 'GET',
    opaque:'npm.json'
}
client.stream(options, ({ statusCode, headers, opaque: filename }) => {
    console.log('response received', statusCode)
    console.log('headers', headers)
    return fs.createWriteStream(filename)
  }, (err) => {
    if (err) {
      console.error('failure', err)
    } else {
      console.log('success')
    }
  })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment