Tips for displaying files from the public folder of express 4.0 as stylized HTML rather than plain files, depending on their extensions. For example, display JSON in a formatted way,

Whenever I place a file in the "public" directory of my express folder, it automatically generates a link on my webpage. For instance, by navigating to , I can download an image. Similarly, clicking on allows me to access a JSON file without any additional steps other than placing the files in the public folder. This feature is incredibly convenient as it saves time and effort, especially when the server needs to handle various items that are subject to frequent modifications.

I am interested in customizing the server command so that instead of immediate downloads, images will be displayed directly within the browser window after adjusting their format using <html> </html>. Additionally, I would like JSON files to be parsed into a readable layout (JSON.stringify(object,null,2)) for easier comprehension and usage.

Essentially, my goal is to effortlessly upload content to the public folder and have instant access to it in a user-friendly manner based on its file extension. For image files, this means viewing them in-browser, while JSON files should be presented in a structured format for better readability.

Answer №1

When it comes to displaying static files in Node.js, it's not as simple as it may seem. The usual approach is to designate a folder as public, where the end URL aligns with the file name. If you're using Express with Node.js, the code typically looks like this:

app.use(express.static(path.join('.', 'public')));

For those who prefer to customize their implementation, there's an alternative method of manually parsing the URL, checking if a file by that name exists, formatting it within HTML, and sending it as a response:

var fs = require('fs');
app.use(function(req, res, next){
    fileName = req.url.substring('https://website.com/'.length);
    if(fs.existsSync('public/'+fileName)){
        if(fileName.substring(fileName.lastIndexOf('.')+1)=='jpg')
            res.send('<html><body><img src="public/'+fileName+'"></img></body></html>')
})

This approach involves checking all URLs for files. Additionally, utilizing a router allows for organizing all public files under a specific subdirectory like '/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

Retrieving various pieces of data in Express

After scouring through various websites, I am still unclear on how to extract multiple GET variables using Express. My goal is to send a request to a Node.JS Express server by pinging the URL with: file_get_contents('http://127.0.0.1:5012/variable1/v ...

Tips for showcasing the array index in Cosmos DB SQL

I'm currently facing an issue with selecting from a document array in Cosmos-DB using the SQL API. While I can successfully retrieve the values from the array, I would like to also be able to display the position of each value within the array. Here ...

What is the best way to achieve maximum height?

Currently, I am attempting to obtain the total height of the page in order to apply it to the styles, specifically for the darkMask class. The reason for needing this height is that when a certain action is triggered within the header, a dark overlay is a ...

Preloading images before loading a div using JavaScript

Can you walk me through implementing object first and then mergeObject in JavaScript? I have an interesting scenario where I need to display the original list followed by a merged list after a short delay. How can I achieve this using JavaScript? Specific ...

Is it possible to create a sticky element that stays fixed to the window without using JavaScript?

Using position: sticky has been a game-changer for me. It resolves many issues without the need for JavaScript. However, I've encountered a roadblock. I am trying to create a sticky element that is nested inside multiple <div> elements. Since po ...

Acquiring the height of the div

I am trying to achieve a specific layout for my webpage. My goal is to make the background color of the red div match the height of the combined heights of the divs with heights 15.56 + 77.33 + 73.33. <body> <!-- outer div --> <div ...

Differences between async/await and then methods in React, demonstration shows that only async/await is functional. Why is

Trying to understand and implement two different API data fetching methods in React app development. The first method involves using the JavaScript Fetch API, while the second method utilizes the async/await syntax. I am currently experimenting with both a ...

Magical Stylist - Eradicate Indicators while Preserving Labeling

Recently, I've been experimenting with the Google styling wizard in an effort to remove markers while retaining labels for businesses. My objective is to eliminate the marker icons but still display the text labels such as "Jimmy Johns," "Boone Saloon ...

Encountering the "excessive re-renders" issue when transferring data through React Context

React Context i18n Implementation i18n .use(initReactI18next) // passes i18n down to react-i18next .init({ resources: { en: { translation: translationsEn }, bn: { translation: translationsBn }, }, lng: "bn ...

Exploring JSON documents one line at a time

What is a more efficient method for parsing a large file filled with individual lines of JSON objects without the need to store each line in a list? ...

What is the best way to remove highlighted text from a textbox that is already selected?

So I have a JS function that I thought was simple, but I'm running into an issue. This function is supposed to select all the text in an ASP.NET textbox (input): function selectAllText(textbox) { textbox.focus(); textbox.select(); } I call t ...

Retrieving JSON data using the fetch method in JavaScript

Currently, I am attempting to retrieve a JSON array using AJAX. Upon calling my test.php file, the following content is returned: [{"name":"James","age":24},{"name":"Peter","age":30}] This is the JavaScript code that I am using: var persons = new Array( ...

Iterating through each ID in a table/cell using .NET MVC with the @

Whenever the table is loaded, I need to run a JavaScript function on each row for cell 4. This function will format the JSON string that is inserted into it. The current code I have only updates the first row/cell... I believe the issue may be related to ...

What steps do I need to take to create a dynamic rowspan within Vuetify?

I am currently working on creating a table that resembles the image provided in the link below. https://i.sstatic.net/xWa1I.png I understand that I can achieve this by using nested data and multiple iterations with the help of the template feature offere ...

Generating elevation graph from a kml file with the combination of php and javascript

Currently, I am exploring the Google Elevation Service with the goal of creating an elevation profile similar to the one showcased in this example: Below is the JavaScript code snippet used: var elevator; var map; var chart; var infowindow = new google.m ...

How does the JsonProperty attribute in Newtonsoft.Json compare to the one in System.Text.Json?

What is the equivalent of System.Text.Json's JsonPropertyName attribute in Newtonsoft.Json? Example: using System.Text.Json.Serialization; public class Example { [JsonPropertyName("test2")] public string Test { get; set; } } References: Sy ...

Guide to opening all href links in a new window

When loading HTML content parsed from an email to a frame, the issue arises when there is an href link that tries to open in the same frame. I want to modify it so that it opens in a new tab instead. Usually, setting the target to _blank in the href would ...

Is it possible to trigger the Facebook Pixel Code using the <noscript> element through programming?

Is there a way to programmatically call the Facebook Pixel Code using noscript? I am facing an issue with the Facebook Pixel Helper extension breaking when the script and noscript code are separated. Can a function be wrapped around the code or built in th ...

What is the best way to create a JavaScript "input" field that only accepts vowel letters?

Is there a way to create an "input" field that only accepts vowel letters? Additionally, I want to ensure that copying and dragging text into the input field will also be filtered out. <div class="field"> <input class="fie ...

Drop down menu not populating with options

I'm trying to automatically bind the second value in a select drop-down menu that I've created using a list of numbers ranging from 0.01 to 10. getNumbers(); function getNumbers() { $scope.numbersArray = []; for (var j = ...