Last active
January 18, 2016 09:13
-
-
Save ovrmrw/e7ad8d7365f670d24b59 to your computer and use it in GitHub Desktop.
sample code to convert data from SQLServer to CSV on Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'babel-polyfill'; | |
import lodash from 'lodash'; | |
const config = require('./config.json') as { mssql: any }; | |
import Sequelize from 'sequelize'; | |
const sequelize = new Sequelize(config.mssql.schema, config.mssql.user, config.mssql.password, { | |
host: config.mssql.host, | |
dialect: 'mssql' | |
}); | |
(async () => { | |
// a query for SELECT from SQLServer. | |
const sql = ` | |
SELECT * | |
FROM yourTable | |
`; | |
const records = await sequelize.query(sql, { | |
type: sequelize.QueryTypes.SELECT | |
}); | |
let columnNames: string[] = []; // array for collecting column names. | |
let lines: (string | number)[][] = []; // array for collecting values as line. | |
records.forEach((record, i) => { // looping per records. | |
let values: (string | number)[] = []; | |
lodash.forEach(record, (value: string | number, fieldName: string) => { // looping per columns. | |
if (i === 0) { // create header line. | |
columnNames.push(`"${fieldName.replace(/"/g, '""')}"`); // escaping " for csv format. | |
} | |
values.push(typeof value === 'number' ? value : `"${value.replace(/"/g, '""')}"`); // if value is string then surrounding by ", and escaping. | |
}); | |
lines.push(values); | |
}); | |
// checking retreived data. | |
console.log(columnNames.join(',')); | |
lines.forEach(values => { | |
console.log(values.join(',')); | |
}); | |
// TODO: write codes for saving data to csv file. | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This sample needs Babel, TypeScript, Sequelize, Tedious and Lodash.