0

So, the question is: I have some files that I need to host for my running app, in order to get all that stuff in response from the HTTP server. If I started the HTTP server in the source folder - then all works fine and I can get all my files. But I need to start the HTTP server above my source folder because I have many of them. Suppose that I have 100 different source folders. is it mean that I need to start 100 servers? To avoid it I wanna run single global HTTP server. Also, I have in my source folders mapping that gives the path (hardcoded) to resources and this path starts from source folder like: source/some_file.png If I run the server in this directory then I will be able to access the file on url http://localhost:8083/some_file.png. But if I start the server in the folder above like: main_dir/source then I cannot access the file http://localhost:8083/some_file.png. And my response fails with error code 404. I've tried to intercept the request and inject the path folder so I get the url file address http://localhost:8083/source/some_file.png. It's working, but then I have different error.. May be there is some other way to start a global http server and access the file one folder below in path?

Yaroslav
  • 486
  • 1
  • 4
  • 14

1 Answers1

0

I've found a doc about serving file with NodeJS built in server: doc. So, 2 possibilities:

  • Serve files yourself with a list
const fs = require('fs');
const http = require('http');

const folderArray = ["main_dir", "another_dir", ...];

http.createServer(function (req, res) {

  folderArray.forEach((folder) => {
  try {
    fs.accessSync(`${folder}/${}req.url` /* Change req.url for your url or parameter */, fs.constants.F_OK);
    console.log('File exists');
    const data = fs.readFileSync(`${folder}/${}req.url`); // Handle this error correctly
    res.writeHead(200);
    res.end(data);
    // You would want to break the loop here as it's already served. 
  } catch (err) {
    console.error('No file!');
  }
  });
}).listen(8080);
  • Or let a module do it for you: node-static (of course, adapte server folder with your folder array :D).

If you want to download the file, check out this answer: download file with express.

Cheers !

DataHearth
  • 484
  • 6
  • 20