[英]How to download a file in node js
我正在嘗試以 .csv 格式下載對象數組。 下面是將數組轉換為 .csv 並存儲在文件 file.csv 中的代碼片段。
let downloadHelper = function(records){
let csvwriter = require('csv-writer');
createCsvWriter = csvwriter.createObjectCsvWriter;
const csvWriter = createCsvWriter({
path: './file.csv'
csvWriter.writeRecords(records).then(() => {
console.log('Done');
});
}
我需要將 file.csv 下載到我的本地。 嘗試使用請求,沒有幫助,因為它只接受 http 請求。 不知道,如何繼續..... 請幫忙
你沒有向我們提供很多信息。 但是使用 Express 你可以做到:
app.get("/", (req, res) => {
res.download("./file.csv", "your-custom-name.csv");
});
如果這對您沒有幫助,請提供有關上下文、您正在使用的框架以及前端的更多信息。
謝謝
例如,您可以像這樣使用 Express:
// Libs
const express = require('express');
const http = require('http');
const path = require('path');
// Setup
const port = 8080;
const app = express();
const httpServer = http.createServer(app);
// http://localhost:8080/download
app.get('/download', (req, res) => {
res.sendFile(path.resolve(__dirname, './file.csv'));
});
// http://localhost:8080/csv/file.csv
app.use('/csv', express.static(path.resolve(__dirname, './csv_files/')));
// Run HTTP server
httpServer.listen(port, () => console.log('Server is listening on *:' + port));
如果您運行此代碼段,您可以打開http://localhost:8080/download
並http://localhost:8080/download
./file.csv。
以下部分代碼負責:
app.get('/download', (req, res) => {
res.sendFile(path.resolve(__dirname, './file.csv'));
});
或者,如果您想訪問整個目錄./csv_files/
您可以這樣做:
app.use('/csv', express.static(path.resolve(__dirname, './csv_files/')));
只需創建./csv_files/foo.csv
文件並轉到http://localhost:8080/csv/foo.csv
。
這對你有意義嗎?
PS工作示例:
// Libs
const express = require('express');
const http = require('http');
const path = require('path');
const fs = require('fs');
// Setup
const port = 8080;
const app = express();
const httpServer = http.createServer(app);
// http://localhost:8080/download
app.get('/download', (req, res) => {
const filename = path.resolve(__dirname, './file' + (new Date()).getTime() + '.csv');
fs.writeFileSync(filename, 'foo,bar,baz');
res.sendFile(filename);
});
httpServer.listen(port, () => console.log('Server is listening on *:' + port));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.