Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda