Menu
CoddyTech

Scrivere un file

Fa parte della sezione Fondamenti di Node.js del percorso Node.js di Coddy. Lezione 11 di 24.

add dimentica la nota appena il programma termina.

writeFileSync(path, text) scrive un file, sostituendo tutto ciò che conteneva. JSON.stringify trasforma un array in testo JSON e null, 2 lo rientra di due spazi, così è più leggibile in Files.

import { writeFileSync } from 'node:fs';

const scores = [12, 40];
scores.push(31);
writeFileSync('scores.json', JSON.stringify(scores, null, 2));

Il file contiene sempre l'intero array: carica le note, ne aggiungi una e le riscrivi tutte. Passare direttamente l'array genera un errore, perché un file contiene testo.

challenge icon

Sfida

Facile
  • add aggiunge la nota e salva tutte le note in notes.json.
  • Stampa Saved note 3. con il numero della nuova nota.

Esegui node notes.js add Buy bread, poi list e apri notes.json in Files. Poi esegui clear e add ancora una volta sul disco vuoto.

Provalo tu

import { existsSync, readFileSync } from 'node:fs';

const file = 'notes.json';

const store = {
    notes: existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : [],
    add(text) {
        this.notes.push(text);
        return this.notes.length;
    },
};

export default store;

Tutte le lezioni di Fondamenti di Node.js