Created
August 21, 2019 12:46
Star
You must be signed in to star a gist
Processing large file with backpressure
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 dynamoose = require('dynamoose'); | |
dynamoose.AWS.config.update({ | |
region: 'eu-west-1' | |
}); | |
const schema = new dynamoose.Schema({ | |
SOMEKEY: { | |
type: String, | |
hashKey: true, | |
}, | |
SOMEDATA: String | |
}); | |
const Model = dynamoose.model('dynamotable', schema); | |
module.exports = Model; |
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 csv = require('csvtojson') | |
const fs = require('fs') | |
const stream = require('stream') | |
const model = require('./model') | |
let total = 36504517 | |
let lineCompleted = 0; | |
const CHUNKAMOUNT = 100 | |
let data = [] | |
class WriteStream extends stream.Transform { | |
constructor() { | |
super() | |
} | |
_write(chunk, encoding, callback) { | |
if (data.length < CHUNKAMOUNT) { | |
data.push(JSON.parse(chunk.toString('utf8'))) | |
callback() | |
} else if (data.length === CHUNKAMOUNT) { | |
model.batchPut(data) | |
.then(() => { | |
lineCompleted += CHUNKAMOUNT | |
console.log(new Date(), 'chunk:', data.length, lineCompleted, '/', total, 'completed:', (lineCompleted / total * 100).toFixed(3), '%') | |
this.push(chunk.toString('utf8')) | |
data = [] | |
callback() | |
}) | |
} | |
} | |
_read() {} | |
} | |
let writeStream = new WriteStream | |
process.on('exit', (code) => { | |
console.log(`About to exit with code: ${code}`); | |
}); | |
const readStream = fs.createReadStream('./data.csv', { encoding: 'utf8'}); | |
readStream | |
.pipe(csv()) | |
.pipe(writeStream) | |
.on('error', (err) => { | |
console.log(err) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment