1

I have recently converted my full web application from PHP to NodeJS.

In Apache, I could use a .htaccess file to perform redirects. The main redirect I had within my application was redirecting all CSS and JS files from a unique name, to their correct path. This was to make sure that when I push an update to my server, all I need to do is change the global variable to have the client load all CSS and JS files from the server instead of from the cache.

For example, in my main PHP file I would include a global variable like so:

define('js_version', "7fn39tg");

Then in my PHP file I would include all JS and CSS files like so:

<script src="content/scripts/my-script__<?php echo js_version ?>.js"></script>

They would then get rendered client slide like this:

<script src="content/scripts/my-script__7fn39tg.js"></script>

Lastly, I would then use .htaccess to read the file from it's original location, being my-script.js:

RewriteRule ^(.+)\_\_(.+)\.(js)$ $1.$3 [L]

How could I do the above in NodeJS?

I'm thinking that I need to use EJS to render the version number inside the template, like so:

app.get('/', function (req, res) {
    res.render(__dirname + '/public/app.ejs', {
       "js_version": "7fn39tg"
    });
});

And include it in my app.ejs file like so:

<script src="content/scripts/my-script__<%= js_version %>.js"></script>

And then use app.use(function(req, res, next){.....} to somehow direct the file to it's actual path. I'm currently serving all static content from the following:

app.use(express.static(__dirname + '/public'));
Fizzix
  • 23,679
  • 38
  • 110
  • 176

1 Answers1

1

You can redirect in Node using res.redirect('/redirect/path')

Cameron Sima
  • 5,086
  • 6
  • 28
  • 47
  • 1
    That's the thing, I don't want it to just `redirect`. With `.htaccess`, the file name would stay the same within my HTML, although when I browsed to `my-script__ 7fn39tg.js`, it would display the contents from `my-script.js`. Although in your method, if I browse to `my-script__ 7fn39tg.js`, it just redirects to `my-script,js`, therefore defeating the purpose of what I'm trying to do here. The browser will load that from cache since it's the same filename. – Fizzix Jun 30 '16 at 01:10