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

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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