DEV Community

Cover image for Show a file with Nodejs.
Elison Sánchez
Elison Sánchez

Posted on

Show a file with Nodejs.

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) => {}
Enter fullscreen mode Exit fullscreen mode

Inside we will use a trycatch to recover errors

const viewDocument = (req,res) => {
try {

    } catch (err) {
        return res.status(500).json(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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)      
        })
Enter fullscreen mode Exit fullscreen mode

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

I hope it helps you.

Top comments (3)

Collapse
 
zippytyro profile image
Shashwat Verma

Can you write your 'about' in english so that everyone can read it?

Collapse
 
zippytyro profile image
Shashwat Verma

Cool.

Collapse
 
bryan074218 profile image
bryan074218

nice post bro