0

so I'm trying to make a handler (sorta) that automatically app.get using fs.readFiles. If that made sense

Here's what I got so far

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

function readFiles(dirname, onFileContent, onError) {
  fs.readdir(dirname, function(err, filenames) {
    if (err) {
      onError(err);
      return;
    }
    filenames.forEach(function(filename) {
      fs.readFile(dirname + filename, 'utf-8', function(err, content) {
        if (err) {
          onError(err);
          return;
        }
        onFileContent(filename, content);
      });
    });
  });
}
var data = {};
readFiles('translogs/', function(filename) {
  data['name'] = filename.split('.').slice(0, -1).join('.');
  console.log(data)
}, function(err) {
  throw err;
});
app.get(`/` + data.name, function (req, res) {
  res.sendFile(`translogs/${data.name}.html` , { root : __dirname});
})

app.listen(3000)

But I keep getting Cannot GET /filename

Everything works its only the app.get(/ + data.name part that doesn't

  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – derpirscher Jul 27 '22 at 21:07
  • It does not. What I'm trying to do is make a script to where I don't have to manually do app.get for every file – SniperrifleXD Jul 27 '22 at 21:15
  • Still your `readFiles` is asynchronous and you are not waiting for it so in the moment you do `app.get('/' + data.name, ...` your `data.name` is still undefined, thus the only route you are actually defining is for `app.get('/undefined', ...)` – derpirscher Jul 28 '22 at 07:07
  • Furthermore, the callback that sets `data['name'] = ...` is called mutliple times, ie once for every file in that directory, so `data.name` is overwritten every time. And as also `fs.readFile` is async, you can't determine, in what order they finish, so the final value of `data.name` is more or less one random filename form your directory. Is that really what you want? – derpirscher Jul 28 '22 at 07:12
  • And if you really want to define distinct route for every file in that directory, you have to call `app.get(...)` once for every file, ie you have to move that into the loop. But you *really don't want* that. Typically you do that by defining a path parameter and then getting the filename to read from that parameter. See the express docs for details. And finally, if you just want to serve a bunch of files, express has a prededined middleware for that `app.use(express.static(...))` – derpirscher Jul 28 '22 at 07:17

1 Answers1

0

Consider using a Python server instead of node.js using the command below.

python3 -m http.server --bind 127.0.0.1 8080

I know it's not really fixing the problem, but it's better if you want it to list all the files in a directory.

astro
  • 1
  • 1
  • 8