Shiva
Shiva

Reputation: 51

How to download a file in node js

I am trying to download array of objects in .csv format. below is the code snippet which converts an array to .csv and get stored in the file 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');
    });
} 

I need to download the file.csv to my local. tried using requests, didn't help as it is accepting only http requests. no clue, how to proceed..... Please help

Upvotes: 0

Views: 300

Answers (2)

Dmitry
Dmitry

Reputation: 183

For example, you can use Express like this:

// 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));

If you run this snippet, you can open http://localhost:8080/download and ./file.csv would be downloaded.

Following part of code is responsible for that:

app.get('/download', (req, res) => {
  res.sendFile(path.resolve(__dirname, './file.csv'));
});

Or if you want to give access to the whole directory ./csv_files/ you can do this:

app.use('/csv', express.static(path.resolve(__dirname, './csv_files/')));

Just create ./csv_files/foo.csv file and go to http://localhost:8080/csv/foo.csv.

Does it make sense to you?

PS Working example:

// 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));

Upvotes: 0

jbergeron
jbergeron

Reputation: 545

You did not provide us a lot of information. But with Express you could do:

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

If this does not help you, please provide more info about the context, framework you are using and what front.

Thank you

Upvotes: 1

Related Questions