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

199
Vistas
How to make a model in another file

I'm beginner and tried to transfer the model to another file, it didn't work for me, suggest me how to do it correctly. The question may seem silly, but if I knew the answer, I would not ask it.

file todo.controller.js

const fs = require("fs");
const { v4: uuidv4 } = require("uuid");

const data = fs.readFileSync("./data/data.json");
let todos = JSON.parse(data);
class todoController { 
async createTodo(req, res) {
    req.on("data", (data) => {
        const jsondata = JSON.parse(data);
        const title = jsondata.title;
        const description = jsondata.description;
        if ((title, description)) {
          todos.push({
            id: uuidv4(),
            title,
            description,
            dateOfCreate: new Date(),
            lastModified: new Date(),
            check: new Boolean(false),
          });
        fs.writeFile(
          "./data/data.json",
          JSON.stringify(todos, null, 2),
          (err) => {
            if (err) throw error;
          }
        );
      }
    });
  }}

file todo.router.js

const url = require("url");
const todoController = require("../controllers/todo.controller");

const todoRouter = (req, res) => {
  const urlparse = url.parse(req.url, true);

  if (urlparse.pathname == "/todos" && req.method == "POST") {
    todoController.createTodo(req, res);
  }
};
module.exports = todoRouter;

here is file data.json data.json

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You have two separate problems here, separating your code to a different file and also saving or persisting that data somewhere, in this case a file.

You have to create something like a data model and then you have to import it in your other code.

// data.js

export const get = async () => {} // we will implement this just now

export const set = async (data) => {} // we will implement this just now

...

// controller.js

import {get, set} from './data.js' // import the methods we just created

...

const createTodo = async (req, res) => {
  req.on("data", (data) => {
    // here you can use get() if you want to use the data

    set(JSON.stringify(data)) // send data to your data model
  }
}

Then we also have to actually do something with those methods.

// data.js

export const get = async () => {
  // may need to use JSON.parse here depending on how you'll use it
  return fs.readFile('./data.json')
}

export const set = async (data) => {
  fs.writeFile('data.json', JSON.stringify(data))
}

So the idea is to have a model responsible for managing the data, retrieving it and saving it, then importing and using those methods in the main controller. The code above isn't perfect, it's just to show you how to think about it.

about 4 years ago · Juan Pablo Isaza Denunciar
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