title: Node.js write SQL query results to CSV
body: <p>I'm currently attempting to query a database with the Node.js library Tedious, then write the results to a CSV file using the library "cdv-write-stream". I'm able to successfully query the DB, get back the results, and write them to a CSV file - However, the script keeps running accessing the file. I'm new to node.js and am not sure what I'm doing wrong.</p>
  
  <p>Relevant Code:</p>
  
  <pre><code>var Connection = require('tedious').Connection;
  var csvWriter = require('csv-write-stream');
  var sql = require('./sql')
  var moment = require('moment');
  var writer = csvWriter();
  const fs = require('fs');
  
  var headers = [];
  var resultRow = [];
  var now = moment().format("MM-DD-YYYY");
  var config = {
      userName: '**',  
      password: '***',  
      server: '***',  
      options: { encrypt: false, database: 'CordaCustom' }
  };
  var connection = new Connection(config);
  connection.on('connect', function (err) {
      // If no error, then good to proceed.  
      executeStatement();
  });
  
  var Request = require('tedious').Request;
  var TYPES = require('tedious').TYPES;
  
  function executeStatement() {
      request = new Request(sql['sql'], function (err) {
          if (err) {
              console.log(err);
          }
      });
      var result = "";
      //Write headers to an array.
      request.on('columnMetadata', function (columns){
          columns.forEach(function (column) {
              headers.push(column.colName);
          });
      });
      //Write headers to CSV file
      var writer = csvWriter({ headers: headers });
      writer.pipe(fs.createWriteStream( 'TL_Statistics' + now + '.csv'));
      request.on('row', function (columns) {
          columns.forEach(function (column) {
              if (column.value === null) {
                  resultRow.push(' ')
              } else {
                  resultRow.push(column.value)
              }
          });
          writer.write(resultRow)
          resultRow = [];
          result = "";
      });
  
      request.on('done', function (rowCount, more) {
          console.log(rowCount + ' rows returned');
  
      });
      connection.execSql(request);
  
  }
  
  writer.on('end', function () {
      connection.close();
  });
  writer.end();
  </code></pre>