Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda