Reputation: 89
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!
Upvotes: 0
Views: 1033
Reputation: 1015
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);
Upvotes: 1