0

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!

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Hi thanks for your reply. I used the same code and changed the filePath to a hardcoded pathname 'C:/Users/.../Downloads/DLTest.txt' (I'm on windows, tried replacing the '/' with '\\') but nothing shows up when I enter localhost:2000 on my browser. Also ideally I want the download to be triggered by a button.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.