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

116
Vistas
How to generate an id when adding an object in node.js

I am trying to append an id to an object if it's the first and if there are others I want to add +1 to one that I am adding.
I am using function that is called save and inside it there is a writeFile and an appendFile method:

class Contenedor {
    constructor (nombre){
        this.nombre= nombre
        this.count = 0
        this.product = []
    }

    save(obj) {

        

        if (this.count <= 1){
            fs.writeFile(`./${this.nombre}`, JSON.stringify(obj), 'utf-8', (err)=> {
                if (err) {
                    console.log("Error al crear archivo")
                } else {
                    this.product.map(x=>{
                        x['id'] = this.count;
                        this.count++
                    })
                    console.log("Archivo creado")
                }
            })

        } else {
            fs.appendFile(`./${this.nombre}`, JSON.stringify(obj), 'utf-8', (err)=> {
                if (err) {
                    console.log("Error al crear archivo")
                } else {
                    this.product.map(x=>{
                        x['id'] = this.count;
                        this.count++
                    })
                    console.log("Archivo agregado")
                }
            })
        }
    }
}

let archivos = new Contenedor('text.json')

archivos.save(
    [
        {
            title: 'Escuadra',
            price: 152.50,
            thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.seawhite.co.uk%2Fimagecache%2F6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
        }
]

I want to have a unique id for the objects. I'm using map() method and already tried this.count++.

Anyone knows how to do it?

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

0

const fs = require('fs');
class Contenedor {
    constructor(nombre) {
        this.nombre = nombre
        this.count = 0
        this.product = []
        this.writelock = false;
        fs.writeFileSync(`./${this.nombre}`, '[');
    }

    save(obj) {
        if (this.writelock) {
            console.log('waiting for a sec');
            setTimeout(() => this.save(obj), 1000);
        } else {
            console.log('started writing', this.count);
            this.writelock = true;
            obj['id'] = this.count;
            let toWrite = JSON.stringify(obj, null, 2);
            if (this.count > 0) toWrite = ', ' + toWrite;
            fs.appendFile(`./${this.nombre}`, toWrite, 'utf-8', (err) => {
                if (err) {
                    console.log("Error al crear archivo")
                } else {
                    this.product.push(obj);
                    this.count++;
                    console.log("Archivo agregado");
                }
                this.writelock = false;
            })
        }
    }

    done() {
        if (this.writelock) {
            console.log('waiting for a sec');
            setTimeout(() => this.done(), 1000);
        } else {
            this.writelock = true;
            fs.appendFileSync(`./${this.nombre}`, ']', 'utf-8', (err) => {
                if (err) {
                    console.log("Error al crear archivo")
                }
                this.writelock = false;
            })
        }
    }
}

let archivos = new Contenedor('text.json')

archivos.save(
        {
            title: 'Escuadra',
            price: 152.50,
            thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.seawhite.co.uk%2Fimagecache%2F6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
        }
)
archivos.save(
        {
            title: 'Escuadra',
            price: 100.50,
            thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.seawhite.co.uk%2Fimagecache%2F6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
        }
)
archivos.save(
        {
            title: 'Escuadra',
            price: 126.50,
            thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.seawhite.co.uk%2Fimagecache%2F6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
        }
)

archivos.done();

Added a write-lock in case save is used multiple times. You can remove that if you are going to add everything in one save only. Added '[' at the start and ']' at end of the JSON file to have a valid JSON file.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Instead of reinventing the wheel and complicating things, just go simple. Use an randomUUID() for you unique id:

const { randomUUID } = require('crypto');
myObject.id = randomUUID();
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