Home > Software design >  How to request a csv file from a url via nodejs?
How to request a csv file from a url via nodejs?

Time:10-04

I'm looking for a way to request a csv file from any url to save it then. If possible only using fs, http, request and express modules.

For testing I tried it with

request('http://localhost:3000/data1.csv').pipe(fs.createWriteStream('data2.csv'))

but i always get as a resonse (data2.csv)

<pre>Cannot GET /data1.csv</pre>

Simplified Code

const fs = require('fs')
const request = require('request')

const express = require('express')
const app = express()

app.listen(3000)

app.get('/download', (req, res) => {
    request('http://localhost:3000/data1.csv').pipe(fs.createWriteStream('data2.csv'))
})

The file data1.csv is saved in the root of my project folder. But is this also the root of my nodejs server from where I started it?

What I'm doing wrong here?

Thanks!

CodePudding user response:

You need to have an explicit handler that returns data1.csv:

app.get('/data1.csv', (req, res) => {
  res.sendFile('data1.csv');
});
  • Related