我想将我的数据导出到csv文件中,为此我在节点js中使用了fast-csv
。它的工作正常我的代码是
var csv = require("fast-csv");
app.get('/file/exportToExcel', function(req, res) {
var whereCondi = {
'Id': req.query.id,
}
var response = {};
table.find(whereCondi, function(err, tableData) {
if (err) {
response.status = 400;
response.message = err.message;
res.send(response);
} else {
var csvStream = csv.createWriteStream({headers: true}),
writableStream = fs.createWriteStream("code.csv");
writableStream.on("finish", function() {
});
csvStream.pipe(writableStream);
for (var i = 0; i < tableData.length; i++) {
csvStream.write({allcodes: tableData[i].code});
}
csvStream.end();
}
});
});
但问题是它保存了我的根文件夹中的csv文件我想在用户点击导出到excel时下载该csv文件请帮帮我。
答案 0 :(得分:0)
writableStream = fs.createWriteStream("coupons.csv");
如果我正确理解你,这看起来就是你的问题。当前代码相对于app文件保存csv文件(基本上在你的情况下在同一目录中)。
尝试类似:
writableStream = fs.createWriteStream("./some/directory/coupons.csv");
答案 1 :(得分:0)
您应该在目录中创建csv文件,然后以相同的方式将其删除
const express = require('express')
const objectstocsv = require('objects-to-csv')
const fs = require("fs")
const app = express()
var data = [
{code: 'CA', name: 'California'},
{code: 'TX', name: 'Texas'},
{code: 'NY', name: 'New York'},
];
const PORT = process.env.PORT || 5000
app.get('/',async(req,res) => {
const csv = new objectstocsv(data);
// Save to file:
await csv.toDisk('./test.csv');
// Download the file
res.download("./test.csv",() => {
//Then delete the csv file in the callback
fs.unlinkSync("./test.csv")
})
})