Serve a dynamically generated .js file in ExpressJS when a specific route is accessed

I am working on developing my ExpressJS app, and I have a specific requirement where I need the route to return a dynamically generated .js file that will be utilized by an html <script> tag. Can anyone provide guidance on how to accomplish this task effectively?

Answer №1

Just because you need the file on the client side doesn't mean it has to be stored on the server side as well. Create a route for the desired file and have the handler return the dynamically generated script.

router.get("/public/js/notafile.js", function(req, res) {
    // This can be more than one line
    res.send("function(){console.log('yey')}");
});

You can utilize a template, such as an underscore template or another type of file that replaces placeholders to create complex functions dynamically.

If you are serving a file that the client expects to be in your /public directory, ensure this is bound before your static binding. For example, place it before:

app.use(express.static(__dirname + '/public'));

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

What is the best way to trigger a unique modal dialog for every element that is clicked on?

I simply want to click on the state and have that state's specific pop-up appear. $("path, circle").on('click', function(e) { $('#info-box').css('display', 'block'); $('#info-box').html($(this ...

Utilizing Three.js to Upload Images and Apply Them as Textures

While attempting to upload an image via URL and set it as a texture, I encountered an issue. The error message THREE.WebGLState: DOMException: Failed to execute 'texImage2D' on 'WebGLRenderingContext': Tainted canvases may not be loaded ...

Compressing a folder in Javascript while maintaining its original structure

Looking for a way to zip a selected folder upon upload using JavaScript on the client side. When users select a folder through the upload button, I want to maintain the same folder structure and zip it before uploading it to the backend server. After doin ...

Error: postman expected an array instead of a string

I encountered an issue while trying to submit form data with multiple fields sharing the same name. The error message "TypeError: expected string but received array" keeps popping up. My suspicion is that the problem lies within Postman. I intend to have ...

How to implement hover effect to show child div within parent div using React.js

Hey there! I'm fairly new to working with react js and currently trying to add some animation to a nested div. The parent div, known as " portfolio-product-item ", showcases a featured image pulled from the WP REST API. Inside this parent div, there&a ...

What is the process of calculating the difference between two time values in PHP?

I have searched everywhere online and tried multiple methods over the past couple of days, but still can't seem to achieve the desired result. My goal is to subtract two different times, for example 22:00:00 - 00:30:00 = 21:30:00 $hourToEatLastMeal = ...

Working with masonry does not involve filling tiny crevices

Check out the DEMO here Experience the FULL Screen DEMO An issue with Masonry: it's not filling small gaps even when there is available space. For example, in a main container with a width of 896px; next to the first container with an orange backgr ...

Illustrating an image in React-Admin sourced from a local directory with the path extracted from mongoDB

When pulling data from my mongoDB server, I'm encountering an issue with displaying the image. Everything else shows up correctly, except for the image. <ImageField source='filename' title="image" /> The filename in question ...

Error Alert - React Hooks: Calling Hook incorrectly

Being new to JS and React, I encountered this error message: Invalid Hook Call when attempting to show and hide a component upon clicking another one. Here is the code snippet that caused the issue: const RenderList = ({data}) => { return data.map(( ...

Adding a new key and value to my JSON dataset

I received the JSON response below: { "PatientSearchResult": { "Patient": [{ "AccountBalanceCalcMethod": 2, "AlternatePatientID": 0, "AssignmentOfBenifits": 0, "CellPhoneNumber1": null, ...

Retrieve the element that triggered the event listener within Nuxt

I am currently developing a Nuxt project where I have set up my component using the code below. The select-parent-container has a click event attached to it. Whenever this event is triggered, I need to identify and return the specific parent container that ...

Achieve compatibility for two different types of route parameters in Vue.js

I am trying to set up nested sets of categories in URLs that lead to specific products, but I'm having trouble with matching the routes correctly. Here are the URLs I want: --- renders a "category.show.vue": /$categorySlug+ app.com/catA/cat ...

Sending a php DateTime object to javascript using Ajax

I sent a php datetime object via ajax. Now, I am able to access it in javascript like this: {"timezone":{"name":"Asia\/Tokyo","location":{"country_code":"JP","latitude":35.65231,"longitude":139.74232,"comments":""}},"offset":32400,"timestamp":147265 ...

How can I create signed URLs for a list of file names?

Currently, I have a setup where my Node / Express backend is fetching files from a secure GCS bucket using the .getFiles() method. The process involves looping through an array of filenames, generating signed URLs for each file, obtaining dimensions using ...

Adjust the datepick plugin to display a calendar pop-up when an icon is selected

I have implemented a jQuery calendar plugin called datepick on my website. I have connected the datepicker to my input field using the following code: $('.dobOnly').datepick(); You can see a working example here: jsFiddle Currently, the calen ...

Tips for retrieving information from an API and displaying it in a table

I'm struggling to retrieve data (an array of objects) from an API using a Token and display them in a table using Material-UI. However, I keep encountering the following error: Uncaught (in promise) SyntaxError: Unexpected token 'A', "Access ...

What is the best way to use JavaScript in an ASP.NET Controller to navigate to a different webpage?

I'm currently developing a website using Angular 1 with an ASP.NET MVC backend. I'm trying to create a link that will gather certain parameters using JavaScript, retrieve the correct URL from a controller, and then redirect the user to a differen ...

Currently, my focus is on creating a robust slash command handler for discord.js version 13

I've been attempting to update my command handler to support slash commands, but I keep encountering an Invalid Form Body error when trying to activate the bot. I'm hesitant to switch handlers since I use this one for all my bots, but I can&apos ...

Disable form submission in MVC using a JavaScript function

In my project, there is an upload.ascx file that will be loaded inside a Jquery Popup. The upload.ascx file contains a File Upload control that uploads .xlsx and .xls files. To validate the file uploads and prevent unnecessary files from being uploaded, I ...

Updates made in the type declaration files are not being displayed

I'm currently working on an express app and I have been trying to add a new property to the Request's class instance. To achieve this, I created a type.d.ts file at the root of my project that looks like this: type User = { name: string } de ...