0

In my project I need to store some text files dynamically and end user should be able to download them from browser. I know the best way is using object store like MINIO or S3 but unfortunately the only way I have is to use in memory storage. So what I am trying to do is: I made a public folder and I exposed it using the following code:

var express = require('express');
var app = express();

//setting middleware
app.use(express.static( 'public')); //Serves resources from public folder


var server = app.listen(5000);

it is as simple as that. Then for testing just to make sure I can download and reach a file I created a public folder with t.txt file in it and when I try:

http://localhost:5000/public/t.txt

I get

enter image description here

So why am I not getting it? Also is what I am trying to achieve will be a good match to scenario and is it doable at all?

Learner
  • 1,686
  • 4
  • 19
  • 38

2 Answers2

1

When you're not specifying a path in app.use(), your app will serve the contents of the directory you're pointing to in express.static() on the root path. Try this:

http://localhost:5000/t.txt

That said, if you want it to be accessible at /public/t.txt, just specify the path:

app.use('/public', express.static('public'))
shkaper
  • 4,689
  • 1
  • 22
  • 35
1

At first use the following line of code:

app.use(express.static(__dirname+'/public')); 

This means that your home directory for static HTML pages is in the "public" folder. Note that the "__dirname" points to the directory of the current js file.

After that, call the following URL from the browser or POSTMAN:

http://localhost:5000/t.txt

As you can see, there is no need to write http://localhost:5000/public/t.txt referring to the "public" folder because you have already specified that in the app.use line.

TareqBallan
  • 156
  • 1
  • 1
  • 8