How to read and write files in NodeJs using a REST API
In this guide we will take a look at how we can save files to the disk, and how to read them as well. We will also create a REST API using express, and provide two endpoints. One for uploading a file, and one for getting a file.
Prerequisites
- Create a new project and do
npm init
and follow the steps - Type
npm install express multer
in your terminal
Create our FileHandler
class
In the root of our project, create a file called FileHandler.js
and add following code
const fs = require("fs"); class FileHandler { readFile(path) { if (fs.existsSync(path)) { return fs.readFileSync(path); } throw new Error(`${path} does not exist`); } writeFile(buffer, path) { fs.writeFileSync(path, buffer); } deleteFile(path) { fs.unlinkSync(path); } } module.exports = FileHandler;
We have created two functions, one for reading files and one for writing. We are using the synchronous
version of the functions, which will lock the main thread. There are options for both of them using asynchronous
operation instead, if that is your preferred way.
Create our server
In the root of the project, create index.js
file and add following code
const express = require("express"); const multer = require("multer"); const FileHandler = require("./FileHandler"); const app = express(); const fileHandler = new FileHandler(); // Specifying a destination folder for the buffer files to be saved const upload = multer({ dest: "uploads/" }); app.get("/file", (req, res) => { const { path } = req.query; res.send(Buffer.from(fileHandler.readFile(path)).toString("base64")); }); // Adding middleware to the endpoint. NOTE: "file" in this case should be matching the name of the <input /> in your form. app.post("/upload", upload.single("file"), (req, res) => { // Multer is adding values to file object in the request const { path, originalname } = req.file; // Reading the buffer from the temp file that Multer is creating const buffer = fileHandler.readFile(path); // Writing to disk with the buffer fileHandler.writeFile(buffer, originalname); // Deleting the temp file fileHandler.deleteFile(path); res.sendStatus(200); }); app.listen(3001, () => { console.log(`Example app listening on port 3001`); });
That's it. As you can see, we are using a third party library, multer
, which is a great lib for saving files from a form to storage. See comments in the code for more info about what is going on.
Try it out in postman
Fill in the form like the image are showing, and fire the request.
You should now see the result like this in your project folder
cat.png
is the uploaded file.
Try GET endpoint
If we fire a GET request for our other endpoint like this: localhost:3001/file?path=cat.png
, we will now get the base64 representation of the file in the response.
Outro
All right, so now we have a fully functional API that are handling file uploads and saving it to the disk. Check out Multer docs on NPM to see more examples on what they offer. Like multi file upload etc.
And please take a look at our how to use these endpoints in React guide as well, where we will demonstrate how we can use this in a real life example.
Have a great one!