How to serve dynamic static files in express JS


I am trying to render static file. I came across the sendFile() method but it is not working with proxy. I need help.
Here is my code.

var express = require('express');
const proxy = require('express-http-proxy');
var process = require('process');

var app = express();
app.set('port', (process.env.PORT || 8080));

app.use('$Variable',  express.static(__dirname + '$Variable'));
app.use('/', proxy(function(request, response) {
  return 'http://localhost:8000' + request.url

setTimeout(function() {
}, 100000);

I want something like this does anyone has idea?
What can I do to replace the $variable with path to my files.
NOTE: $VARIABLE is just there to showcase what I am trying to mean. It does not means that I am trying to use PHP in node.js. Think before you become a professor.


To take the path from the URL and append "/webapp" onto the end of it and then look for a file in your file system that matches that to serve, you could do this:

const path = require('path');

app.get((req, res, next) => {
    const file = path.join(__dirname, req.path, "webapp");
    res.sendFile(file, { dotfiles: "deny" }, (err) => {
        if (err) {
            // decide what you want to do here with an error
            // either call next(err), call next() to continue routing
            // or send a 404 response

Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published