Вывод JSON не отображается правильно, JavaScript - PullRequest
0 голосов
/ 29 мая 2018

Я создаю класс в javascript для вывода config.json

const fs = require('fs');

class config {
    static put(input1,input2) {
        let json = {
            input1 , input2 }
        json = JSON.stringify(json);
        fs.writeFile('./config.json', json, (err) => {
            if (!err) {
                console.log('done');
            }
        });
    }
}

config.put('site_name', 'Blog');       
config.put('maintenance', false);   
config.put('age', 30);                  
config.put('meta', {"description": "lorem ipsum"}); 

выведет config.json следующим образом

{"input1":"meta","input2":{"description":"lorem ipsum"}}

Я ожидаю вывода config.json

{ input1: 'site_name', input2: 'Blog' }
{ input1: 'maintenance', input2: false }
{ input1: 'age', input2: 30 }
{ input1: 'meta', input2: { description: 'lorem ipsum' } }

Ответы [ 2 ]

0 голосов
/ 29 мая 2018

Флажком параметров по умолчанию для writeFile является 'w', который будет перезаписывать, вам нужно будет указать 'a' для добавления.

См. Здесь: https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback и здесь для флагов файловой системы:https://nodejs.org/api/fs.html#fs_file_system_flags

0 голосов
/ 29 мая 2018

Используйте команду добавления вместо записи

const fs = require('fs');

class config {
    static put(input1,input2) {
        let json = { input1 , input2 };

        json = JSON.stringify(json);

        fs.appendFile('./config.json', json, (err) => {
            if (!err) {
                console.log('done');
            }
        });
    }
} 
...