Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

228
Views
How to use fs.readFile() and fs.writeFile() in node js to store an image in the project and then in MongoDB

I am working on the backend of a MERN app where, using postman, I have to upload jpg/jpeg... files that stores first in a directory "files" in my project and then in the File collection in MongoDB with ID as name ([id].jpg) . I have to use fs.readFile() and fs.writeFile() to do it, but the max result I obtained is "undefined". The files temporarly stores in a folder on my pc and i don't know how to change this. Moreover I have to obtain the extension of the file, and they suggested me to use const array = file.name.split(“.”); const extension = array[array.length - 1].toLowerCase();

THIS IS MY MODEL:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const FileSchema = new Schema({
fileName: {
    type: String,
    required: true,
},
fileType: {
    type: String,
    required: true,
},
extension: {
    type: String,
    required: true,
},
size: {
    type: String,
    required: true,
},
});

module.exports = File = mongoose.model('file', FileSchema);

THIS IS MY UPLOAD FILE:

const File = require("../../models/File");
const express = require("express");
const formidableMiddleware = require("express-formidable");
const app = express();
app.use(formidableMiddleware());
const fs = require("fs");

module.exports = async (req, res) => {

  const test = ({ file } = req.files);
  console.log("the files store temporarly here", test["file"]["path"]);

  try {
    fs.readFile("C:\Users\grazi\AppData\Local\Temp", 'utf-8', (err, data) => {
      console.log(data);
    });
  } catch (e) {
    console.log(e);
  }

  try {
    fs.writeFile("C:\Users\grazi\wa\Service-stats2\backend\files", 'C:\Users\grazi\wa\Service-stats2\backend\models\File.js', (err, data) => {
      console.log(data);
    });
  } catch (e) {
    console.log(e);
  }
};

IF I SEND A REQUEST WITH POSTMAN THIS IS THE OUTPUT OF MY TERMINAL:

the files store temporarly here:
C:\Users\grazi\AppData\Local\Temp\upload_753ecef1d508a15025b20a29e07e65a3
undefined
undefined
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!