我目前正在尝试使用Node.js库查询数据库繁琐,然后使用库" cdv-write-stream"将结果写入CSV文件。我能够成功查询数据库,获取结果并将其写入CSV文件 - 但是,脚本一直在运行以访问该文件。我是node.js的新手,我不确定我做错了什么。
相关守则:
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();