如何在Node JS中下载文件

时间:2019-12-17 03:15:46

标签: javascript 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请求。不知道,如何进行.....请帮助

2 个答案:

答案 0 :(得分:1)

您没有向我们提供很多信息。但是使用Express可以做到:

app.get("/", (req, res) => {
  res.download("./file.csv", "your-custom-name.csv");
});

如果这对您没有帮助,请提供有关上下文,正在使用的框架以及前端的更多信息。

谢谢

答案 1 :(得分:0)

例如,您可以像这样使用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,然后将下载./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));