Created
January 15, 2015 22:31
-
-
Save aepyornis/2341a13b2658b3c62b48 to your computer and use it in GitHub Desktop.
writeCSV
This file contains hidden or 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
function writeCSV(columnNames, fileName, query, callback){ | |
var db = mongojs('mongodb://localhost:27017/test', ['jobs']); | |
//array of columnNames | |
var columns = []; | |
//ensure that columnNames is array | |
if (typeof columnNames === 'string') { | |
columns.push(columnNames); | |
} else if (columnNames.constructor === Array) { | |
columns = columnNames; | |
} else { | |
console.log('columnNames is not a string or an array'); | |
throw err; | |
} | |
//ensure query is object | |
if (typeof query !== 'object') { | |
query = {}; | |
} | |
//create write stream | |
var file = fs.createWriteStream(fileName + '.csv'); | |
//write headers | |
file.write(columns.join()); | |
file.write('\n') | |
//create cursor | |
var cursor = db.jobs.find(query); | |
//listen for each document | |
cursor.on('data', function(doc){ | |
//write fields for each document | |
columns.forEach(function(columnName, index, arr){ | |
var field = '' + doc[columnName]; | |
file.write(field); | |
//prevents trailing comma | |
if(index !== (arr.length - 1)) { | |
file.write(','); | |
} | |
}) | |
//start new line | |
file.write('\n'); | |
}) | |
//functions to call when cursor is finished | |
cursor.on('end', function(){ | |
//end write stream | |
file.end() | |
//close database | |
db.close(); | |
//optional callback() | |
typeof callback === 'function' && callback(); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment