我目前正在尝试使用 Node.js 库 Tedious 查询数据库,然后使用库“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();