Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
Downloading File From Client Side Node.js

so I am trying to build a website that allows users to download files that are located in the server computer when the users access the website and click a download button.

I wish to use as few libraries as possible due to some real world limitations. Ideally no Express or Ajax. And I think it should be fully possible with just vanilla node.js

From my search on the internet it seems most of the code is of this form:

const fs = require('fs');
const https = require('https');
  
// URL of the image
const url = 'GFG.jpeg';
  
https.get(url,(res) => {
    // Image will be stored at this path
    const path = `${__dirname}/files/img.jpeg`; 
    const filePath = fs.createWriteStream(path);
    res.pipe(filePath);
    filePath.on('finish',() => {
        filePath.close();
        console.log('Download Completed'); 
    })
})

However, the code doesn't seem to be doing what I want. First, it requires an url, so it is more about directing a resource online to another location. Whereas I want to actually serve a locally stored file on the server to users when they access the website.

Second, it appears to be downloading to the server computer. But what I want is to let users download to their own client devices. Basically the normal download function you would encounter when you want to download something on the Internet and you see your browser's "Download" section having some new entries.

How can I achieve what I want?

I'm a total noob at this, so it would be great if I can get a skeleton code with some dummy file or pathname.

Appreciate any guidance. Thanks!

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

You are missing an http.server. http.get just does a web request and as you said you don't want to do that.

Here is some example code creating a server and serving a single file without using express:

const fs = require('fs');
const path = require('path');
const http = require('http');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, '/files/img.jpeg');

    response.writeHead(200);

    var readStream = fs.createReadStream(filePath);
    readStream.pipe(response);
}).listen(2000);
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!