I use request module to download a zip file that cointain a .csv file, then i use pipe to read the content with unzip and split modules and then i parse and write result into mongodb with mongoose-object-stream module.
My code:
//index.js
var request = require('request');
var bun = require('bun');
var split = require('split');
var unzip = require('./lib/unzip');
var tomongo = require('./lib/tomongo');
var pipeline = bun([ unzip(), split()]);
request.get( "http://someurl/somefile.zip" )
.pipe( pipeline )
.pipe( tomongo() );
//tomongo.js
var mySchema = require('../schema.json');
var through = require('through2');
var mos = require('mongoose-object-stream');
var mongoose = require('mongoose');
var models = require('../models')
const dbpath = "mongodb://localhost:27017/test";
const mongo = mongoose.connect(dbpath, {useNewUrlParser: true });
mongo.then(() => {
console.log('mongoDB connected');
}).catch((err) => {
console.log('err', err);
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
var modelStream = new mos(models.books);
function parser(){
var columns = mySchema;
var parseandwrite = function( chunk, _, cb ){
var row = {}, cells = chunk.toString('utf-8').split('\t');
cells.forEach( function( cell, i ){
row[ columns[ i ] ] = ( cell || '' ).trim();
});
if( !!chunk ){
modelStream.write( row );
}
cb();
};
return through.obj( parseandwrite );
}
module.exports = parser;
I want to do something when the stream ends and all records are stored in the db.
I tried adding to pipe .on('finish', function(){process.exit()}) or .on('end', function(){process.exit()}) but node continue running.