![]() |
VOOZH | about |
The res.sendFile() function in Express.js is a convenient method for sending static files (like HTML, PDFs, images, or other media) directly to the client. It transfers the file at the given path and it sets the Content-Type response HTTP header field based on the filename extension.
Syntax
res.sendFile(path [, options] [, fn])Parameter
Returns: It returns an Object.
Step 1: Run the following commands to initialise the project.
npm init -yStep 2: Installing required packages
npm install expressFolder Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^5.1.0",
}Step 3: Create a index.js, .env and a text file and implement the res.sendFile() function using the code provided.
In the Hello.txt file add the following text
Greetings from GeeksforGeeksRun the application using the following command
node index.jsOutput: Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output:
Server listening on PORT 3000
Sent: Hello.txtHandling errors properly is crucial to ensure the client receives a proper response when something goes wrong (e.g., if the file doesn’t exist or can't be accessed). Express allows you to pass a callback function to handle errors.
In this example
The res.sendFile() function in Express is a simple and efficient way to serve static files like HTML, PDFs, images, and more directly from your server to the client. By providing the correct file path, optional settings, and an error handling callback, you can easily manage file serving in your web applications.