Created
January 29, 2024 16:29
-
-
Save diegoachury/663ff9bd15c34ae12723050395cb4f91 to your computer and use it in GitHub Desktop.
a exportar 100,000 registros en lotes de 20,000 utilizando Node.js
This file contains 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 createCsvWriter = require('csv-writer').createObjectCsvWriter; | |
// Función simulada para obtener datos (reemplazar con tu lógica de base de datos) | |
async function obtenerDatos(offset, limit) { | |
// Aquí iría tu lógica para obtener los datos | |
// Por ejemplo: SELECT * FROM tu_tabla LIMIT ${limit} OFFSET ${offset} | |
return []; // Retorna los datos | |
} | |
// Función para escribir un lote de datos en un archivo CSV | |
async function escribirEnCSV(datos, archivo) { | |
const csvWriter = createCsvWriter({ | |
path: archivo, | |
append: true, | |
header: [ | |
// Definir las columnas aquí, por ejemplo: | |
// {id: 'id', title: 'ID'}, | |
// {id: 'nombre', title: 'Nombre'} | |
] | |
}); | |
await csvWriter.writeRecords(datos); | |
} | |
// Función principal para exportar los datos | |
async function exportarDatos() { | |
const TOTAL_REGISTROS = 100000; | |
const REGISTROS_POR_LOTE = 20000; | |
const archivoCSV = 'ruta/a/tu/archivo.csv'; | |
for (let offset = 0; offset < TOTAL_REGISTROS; offset += REGISTROS_POR_LOTE) { | |
const datos = await obtenerDatos(offset, REGISTROS_POR_LOTE); | |
await escribirEnCSV(datos, archivoCSV); | |
console.log(`Exportados ${offset + datos.length} de ${TOTAL_REGISTROS} registros`); | |
} | |
console.log('Exportación completada.'); | |
} | |
exportarDatos().catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment