Transitioning from using sendfile() to sendFile() function within the Express framework

Here is the code snippet I am using:

router.get('/image',(req,res,next)=>{
  const fileName = "path_to.jpg"
  res.sendfile(fileName,(err)=>{
    if (err) {
      next(err);
    } else {
      console.log('Sent:', fileName);
    }
  });
})

While this router works in Express 4 by sending the desired image successfully to the client, there is a warning from the server stating that "res.sendfile" is deprecated and recommending the use of "res.sendFile" (simply capitalizing the "f").

express deprecated res.sendfile: Use res.sendFile instead

However, when I make this change as suggested, my code no longer produces a 200 status but rather a 500 error. This happens with only the alteration of changing the letter case for "file".

Am I misunderstanding what the express warning is trying to convey?

I have checked the Express documentation and do not see any evident mistake in my code snippet... If there are additional details needed, please let me know.

Answer №1

After integrating the "path" module into the router, I am now able to generate an absolute path for sendFile() method to utilize, as advised by @karthick in the original post's comment.

Therefore, when invoking sendFile(), make sure to use a relative path for the fileName parameter and an absolute path generated by "path" for the root option.

The following example assumes that the image file is located in the same directory as the router script:

router.get('/image', (req, res, next) => {
    const fileName = "1.jpg";
    res.sendFile(fileName, { root: path.join(__dirname, './') }, (err) => {
        if (err) {
            console.log(err);
            next(err);
        } else {
            console.log('Sent:', fileName);
        }
    });
})

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

When initially loaded, the Bootstrap Datepicker displays an inaccurate calendar

I implemented Bootstrap Datepicker to insert a date input field into my HTML document. Below is the code I used: HTML: <input type="text" name="manifest-date" class="calendar form-control" placeholder="M-d-yy" id="manifest-date" value="{{$currentDate} ...

Utilizing a modular perspective in JavaScript to load JSON files as a view

I've been working on implementing a modular view approach for retrieving data from a JSON file in my JavaScript code, but I'm facing some issues. The snippet of code where I am trying to load the JSON file is contained within a separate JS file a ...

Equalize the color of overlapping background events with non-overlapping background events in fullcalendar

events:[ {overlap:false, display:'background', start:'2021-12-23 10:15:00', end:'2021-12-23 10:30:00'}, {overlap:false, display:'background', start:'2021-12-23 10:30:00', end:'2021-12-23 10:45:00&a ...

Converting coordinates of latitude and longitude into JSON format

I'm currently facing some challenges with organizing map waypoints, defined by latitude/longitude pairs, within a JSON array. This is the progress I've made so far. var llData = {}; var waypointData = {}; for (i = 0; i < routeArray.length; ...

A warning is triggered when attempting to return a non-returning function from a Promise

I have a nodejs express app where I am utilizing a library that operates on a typical callback interface for executing functions. However, my persistence layer is set up using a promise-based approach. The following code snippet is causing me some concern: ...

Getting information from my RESTful API and populating the array data property in my VueJS component

For several weeks, I've been immersed in learning Vue.js and building a Rest API backend using NodeJS express, which I'm eager to integrate. After successfully setting up the Rest API to deliver JSON data, my next challenge is to retrieve that js ...

Enhancing Web Service Calls with Angular 2 - The Power of Chaining

I am currently facing an issue where I need to make multiple web service calls in a sequence, but the problem is that the second call is being made before the .subscribe function of the first call executes. This is causing delays in setting the value of th ...

Creating an interface that accurately infers the correct type based on the context

I have an example below of what I aim to achieve. My goal is to start with an empty list of DbTransactInput and then add objects to the array. I experimented with mapped types to ensure that the "Items" in the "Put" property infer the correct data type, w ...

JavaScript and jQuery syntax are essential for web development. Understanding how

I've been searching everywhere but couldn't find syntax similar to this: var mz = jQuery.noConflict(); mz('#zoom01, .cloud-zoom-gallery').CloudZoom(); This basically means: jQuery.noConflict()('#zoom01, .cloud-zoom-gallery') ...

Tips for passing data to a child component from a computed property

Currently in the process of setting up a filter using vue-multiselect. Everything seems to be working fine, but there's one issue I can't seem to resolve. Upon page reload, the label (v-model) appears empty. The root cause seems to be that the v ...

Utilize the express library (NodeJS, TypeScript) to send back the results of my function

I am curious about how I can handle the return values of my functions in my replies. In this specific scenario, I am interested in returning any validator errors in my response if they exist. Take a look at my SqlCompanyRepository.ts: async create(compan ...

Execute controller action upon item selection within KODataTable MVC table

I am displaying data in a table using AJAX to call an Action that returns a JSON list. Output: I want each user (row in the table) to be clickable and linkable to an edit page (Admin/Edit/Id). This can be done either by clicking on them or by having an E ...

Tips for modifying the value of a JSON object using Javascript or Jquery

I am looking to retrieve the value of a specific key, potentially accessing nested values as well. For example, changing the value of "key1" to "value100" or "key11" to "value111. { "key1": "value1", "key2": "value2", ...

Using ChartsJs to visualize input data formatted in the German data format

I am relatively new to working with Charts.js, but I will need it to generate some visually appealing graphs for my website. In the background, I have a Django project running that calculates a specific set of numbers for me. Due to the language setting in ...

No matter what I try, the Mongoose query consistently comes back with

I've been attempting to perform a query where I find products with an ID greater than a specified minimum, but it always returns an empty array. const productSchema = require("./productsSchema"); const getProductsGreaterThan = async (min ...

How is it possible that my code is continuing to run when it is supposed to be

My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders based on their URLs and store the ones that return data in successfulResponses within my app.component.ts. Promise.all( orders.ma ...

Can a File Object be transmitted to an AWS Lambda function via API Gateway using JavaScript?

Can a JavaScript File Object be passed from a browser to AWS Lambda via API Gateway (ultimately to S3)? I am working with TypeScript and React. Environment Frontend TypeScript React AWS Amplify (for API module) Backend(AWS Lambda) Node.js Expecta ...

Angular and JavaScript Performing Slide-Up Animation

Currently, I am working on creating a menu using Angular and JavaScript. My goal is to have this menu toggle between showing and hiding when a button is clicked. If you would like to view the code that I have written so far, you can check out the demo her ...

Is there a way to group together select values in a dropdown menu under a shared category?

If I have a dropdown menu that looks like for example: <select> <option value="1">1</option> <option value="3">3</option> <option value="2">2</option> <option value="4">4</option> </select&g ...

Encountered a issue during the installation of an NPM module

I am a beginner in the world of web development. I attempted to set up an npm module using the command npm install grunt-contrib-watch --save-dev, however, I encountered the following error: npm WARN npm npm does not support Node.js v0.10.37 npm WARN npm ...