Estoy tratando de agregar una identificación a un objeto si es el primero y si hay otros, quiero agregar +1 a uno que estoy agregando.
Estoy usando una función que se llama save y dentro de ella hay un método writeFile y appendFile :
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' } ] Quiero tener una identificación única para los objetos. Estoy usando el método map() y ya probé this.count++ .
¿Alguien sabe como hacerlo?
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();Se agregó un bloqueo de escritura en caso de que se use guardar varias veces. Puede eliminar eso si va a agregar todo en un solo guardado. Se agregó '[' al principio y ']' al final del archivo JSON para tener un archivo JSON válido.
En lugar de reinventar la rueda y complicar las cosas, hazlo simple. Use un UUID aleatorio () para su identificación única:
const { randomUUID } = require('crypto'); myObject.id = randomUUID();