node-etl icon indicating copy to clipboard operation
node-etl copied to clipboard

How to Export to csv file?

Open stevenluoxiaohua opened this issue 10 years ago • 3 comments

`p.stream('select * from users')

.pipe(etl.stringify(0,null,true)) .pipe(etl.toFile('txt/test.txt')) .promise() .then(function() { console.log('done') }) .catch(function(e) { console.log('error',e); });`

I'm try like this, but how to do next?

stevenluoxiaohua avatar Jul 31 '16 04:07 stevenluoxiaohua

A very simple example would be something like:

// assuming mysql client for the select
client.query('select * from users').stream()
  .pipe(etl.map(function(d) {
    // if we haven't sent headers, we start by doing so
    if (!this.headers)
      this.headers = this.push('"'+Object.keys(d).join('","')+'"\n') || true;
    return '"'+Object.keys(d).map(key => d[key]).join('","')+'"\n';
  })
  .pipe(etl.toFile('txt/text.txt'))
  .promise()
  .then(...)

However this does not properly escape the fields. A safer bet would be to use something like csv-write-stream which I believe you can use like this:

var csvWriter = require('csv-write-stream');

client.query('select * from users').stream()
  .pipe(csvWriter())
  .pipe(etl.toFile('txt/text.txt'))
  .promise()
  .then(...)

Let me know if this works or not for you

ZJONSSON avatar Jul 31 '16 23:07 ZJONSSON

thanks, It works ok, code as follows

`var pool = mysql.createPool({ host: 'localhost', port: '3306',

database: 'gss'

});

var p = etl.mysql.execute(pool);

p.stream('select * from test') .pipe(csvWriter({ separator: ',', newline: '\n', headers: undefined, sendHeaders: false })) .pipe(etl.toFile('txt/text.txt')) .promise() .then(function () { console.log('done') });`

now, I try insert to database using mysql

stevenluoxiaohua avatar Aug 01 '16 04:08 stevenluoxiaohua

see https://github.com/ZJONSSON/node-etl/issues/31 for the other question

ZJONSSON avatar Aug 01 '16 23:08 ZJONSSON