Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function exportToCsv(filename, rows) {
var processRow = function (row) {
var finalVal = '';
for (var j = 0; j < row.length; j++) {
var innerValue = row[j] === null ? '' : row[j].toString();
if (row[j] instanceof Date) {
innerValue = row[j].toLocaleString();
};
var result = innerValue.replace(/"/g, '""');
if (result.search(/("|,|\n)/g) >= 0)
result = '"' + result + '"';
if (j > 0)
finalVal += ',';
finalVal += result;
}
return finalVal + '\n';
};
var csvFile = '';
for (var i = 0; i < rows.length; i++) {
csvFile += processRow(rows[i]);
}
var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
function emit(method, data) {
return new Promise((resolve, reject) => {
window.socket.emit(method, data, (err, result) => {
if (err) {
reject(err);
} else {
setTimeout(() => resolve(result), 1000);
}
});
});
}
function getAllPosts(topicId) {
return new Promise((resolve, reject) => {
let idx = 0, result = [];
const iterate = () => emit('topics.loadMore', {
tid: topicId,
after: idx,
direction: 1
}).then((results) => {
if (!results.posts || !results.posts.length) {
return resolve(result);
}
idx += results.posts.length;
result = result.concat(results.posts)
return Promise.resolve().then(iterate).catch(reject);
}).catch((err) => reject(err));
iterate();
});
}
function downloadTopic(topicId) {
return getAllPosts(topicId).then(posts => {
let rows = [['pid','uid','username','timestamp','content']];
posts.forEach(post=>{
rows.push([post.pid,post.uid,post.user.username,post.timestampISO,post.content]);
});
exportToCsv(`${topicId}.csv`, rows);
return rows;
});
}
downloadTopic(20937).then(result=>console.log(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment