Hello, this time I want to share a small code that shows how to create a function that allows displaying a file with nodejs. At a time when the need arises to be able in our API to create an endpoint that allows generating a saved file from the back-end.
As a first step we will create a controller that will allow us to generate the functionality
const viewDocument = (req,res) => {}
Inside we will use a trycatch to recover errors
const viewDocument = (req,res) => {
try {
} catch (err) {
return res.status(500).json(err)
}
}
Now if we can start with the logic, with the node path module we are going to recover the address of the file that we are going to show
let filepath = path.join(__dirname,"../public/archive","file.pdf")
fs will do the job, with its readFile property it will read the path and take the file. With the callback we hope to evaluate the error if there is none, we use the res property, contentType where we assign the media type of the resources and then with the send property we send the file.
fs.readFile(filepath, (err,data) => {
if(err){
return res.status(500).json(err)
}
res.contentType("application/pdf")
res.send(data)
})
The complete code looks like this:
const fs = require("fs");
const path = require("path");
const viewDocument = (req,res) => {
try {
let filepath = path.join(__dirname,"../public/archive","file.pdf")
fs.readFile(filepath, (err,data) => {
if(err){
return res.status(500).json(err)
}
res.contentType("application/pdf")
return res.send(data)
})
} catch (err) {
return res.status(500).json(err)
}
}
I hope it helps you.
Top comments (3)
Can you write your 'about' in english so that everyone can read it?
Cool.
nice post bro