Combine, condense, and distribute JavaScript files using Express without applying gzip compression to the response

Currently, I am developing a web application using Express. My goal is to merge, minify, and serve .js files efficiently. To achieve this, I have created a middleware with the following code:

var fs = require('fs'),
    path = require('path'),
    uglify = require('uglify-js'),
    cache = '',
    scriptsDir = path.join(__dirname, '../scripts'),
    files = fs.readdirSync(scriptsDir);

// Since the code runs on startup, synchronous read is acceptable
files.forEach(function(fname) {
    if (/^.*\.js$/.test(fname)) {
        cache += fs.readFileSync(path.join(scriptsDir, fname), 'utf8').toString();
    }
});
cache = uglify.minify(cache, { fromString: true }).code;

module.exports = function(req, res, next) {
    if (req.url === '/js/all.js')
        res.end(cache);
    else
        next();
};

This middleware should be used as shown below:

app.use(compress());
[...]
app.use(app.router);
app.use(jsMerger); // This is where my middleware is invoked
app.use(express.static(path.join(__dirname, '../public')));

The issue at hand is that the response is not gzipped, and it lacks essential headers such as cache headers and etags. The current response looks like this:

X-Powered-By: Express
Transfer-Encoding: chunked
Date: Wed, 12 Mar 2014 14:04:19 GMT
Connection: keep-alive

I am seeking guidance on how to compress the response effectively. Any insights or suggestions would be greatly appreciated.

Answer №1

Upon adding the

res.set('Content-Type', 'text/javascript')
line, Express started gzipping the response. Here is the code snippet:

module.exports = function(req, res, next) {
    if (req.url === '/js/all.js') {
        res.set('Content-Type', 'text/javascript');
        res.end(cache);
    } else {
        next();
    }
};

The response headers now include:

X-Powered-By: Express
Vary: Accept-Encoding
Transfer-Encoding: chunked
Date: Wed, 12 Mar 2014 14:45:45 GMT
Content-Type: text/javascript
Content-Encoding: gzip
Connection: keep-alive

This behavior is due to the design of the compress middleware. By providing a filter option to compress, you can control when compression is applied. Here is an example using the filter:

app.use(express.compress({
    filter : function(req, res) {
        return /json|text|javascript/.test(res.getHeader('Content-Type'));
    }
});

Compression will only be applied to requests that match the filter criteria. If no Content-Type header is provided, the request will not meet the filter's conditions and Express will not gzip the response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enter information into the TextArea and jQuery dialog

I require assistance in populating a textarea with data obtained from querying a database. I have a jQuery dialog that contains another dialog, inside of which is a textarea. Here is some pseudocode: <MODAL> <modalB> <TextArea>s ...

Troubleshooting video streaming loading issues caused by 404 errors in URL paths with videojs

I've been successfully using the video.js library to stream live video. Everything was going well until after a while, the URL started throwing a 404 error during streaming, causing the entire player to get stuck on loading. Now I'm looking for a ...

Using Cookies with Next.js and Vercel

I am facing an issue with my NextJs app deployed on Vercel where the cookie is not being set. Upon checking the console in Network, I can see that the request returns a 200 status and the set-cookie value is present without any warning. However, when I loo ...

TranslateY animation glitching

I need help with expanding a box to 100% height after click, then collapsing and sticking to the bottom. I created a function in Vue framework to handle the animation, but it's not working smoothly. How can I make it less buggy? Check out the demo her ...

Customize the URL path in Next.JS according to the user's location

My Next JS website is hosted on the domain abc.com. I would like the site to automatically detect a visitor's location, retrieve their country code, and then redirect them to abc.com/country_code. ...

What could this error be in Chrome console: "Uncaught SyntaxError: Unexpected token ':'"

Why am I getting this error in the Chrome console: "Uncaught SyntaxError: Unexpected token ':'"? I have a JSON file located at the root of my application: <script src="levels.json"></script> Here is the content of my JSON file: { ...

Using AJAX to submit a form to a CodeIgniter 3 controller

I am working on adding a notification feature and need to run an ajax query through the controller when a button is clicked. Here's the script I'm using: $('#noti_Button').click(function (e) { e.preventDefault(); ...

Ways to verify the presence of an element in a list

I found this interesting JS code snippet: ;(function ($) { $('.filter-opts .opt').click(function(){ var selectedName = $(this).html(); $('.append').append('<li>' + selectedName + '</li> ...

Learn how to install an NPM package as if it were any other

Looking to install the package com.cordova.plugin.cache along with its content, also requiring it to be accessible as cordova-plugin-cache. An example of how the package.json should be structured: "dependencies": { // Both entries are essentially the ...

Invoke a function in JavaScript just once using a closure

I have a JavaScript function that I want to call only once, using closure. Here's the code snippet: function initialize() { let called = 0; return function() { if (called > 0) { return } else { called++; console.log(&a ...

Unable to set background-image on Node (Limited to displaying only images sourced from Flickr)

I am experiencing difficulty with the background-image node property not functioning properly. In order to test this issue, I am using the "Images & breadthfirst layout" demo as an example (accessible at https://gist.github.com/maxkfranz/aedff159b0df0 ...

Troubleshooting Angular JS loading problems

I'm attempting to implement the Angular-Spinner in my project: Specifically, I want to use it with http.get calls. This is what I have so far: Within controllers: $scope.loading = true; $http.get('js/data/test.json').success(function(resu ...

Error Encountered: RSA Key Pairs Invalid Signature for JSON Web Token (JWT)

I am facing an issue with my Node.js application (version 20.5.1) regarding the verification of JSON Web Tokens (JWT) using RSA key pairs. The specific error message I am encountering is: [16:39:56.959] FATAL (26460): invalid signature err: { "type& ...

The next.js router will update the URL without actually navigating to a new page, meaning that it will still display the current page with the updated URL

My search results are displayed at the route /discovery, and I am working on syncing the search state with URL query parameters. For example, if a user searches for "chicken," the URL becomes /discovery?query=chicken&page=1. When a user clicks on a se ...

A guide to dynamically extracting values from JSON objects using JavaScript

I have a JSON array with a key that changes dynamically (room number varies each time I run the code). My goal is to access the inner JSON array using this dynamic key. Here's what I've attempted so far, but it's throwing an error. Here is ...

Could the autofill feature in Chrome be turned off specifically for Angular form fields?

Even after attempting to prevent autofill with autocomplete=false and autocomplete=off, the Chrome autofill data persists. Is there a method to disable autofill in Angular forms specifically? Would greatly appreciate any recommendations. Thank you. ...

The process of developing intents for the Alexa-App involves creating separate files specifically for each intent. These dedicated files are then

To simplify my file management and ensure each intent is in its own file, I am looking for a way to include the intents in my index.js. Here is an example of what I have attempted so far: const alexa = require('alexa-app'); const app = new alexa ...

Struggling to make EJS button functional on the template

I am currently facing an issue with a loop that populates a webpage with multiple items, each containing an image, text, button, and a unique ID associated with it. Although I have written a function to retrieve the ID and plan name when the button is clic ...

Secure your routes by verifying status on a separate server using JSON Web Token authentication service in NodeJS

Currently, I am working on a project where I am developing an API using Node/Express/Mongo and also building a website with the same tools. I would like to host these on separate servers for scalability purposes. For authentication, I have implemented jso ...

How to output a string in jQuery if it includes a certain character?

I need to extract all strings that include a specific word within them, like this: <div> <div> <span> <h3>In Paris (Mark Bartels) worked for about 50 years.</h3> </span> </div> ...