The text file stores:

{"login": "art@mail.ru", "password": "456adf"} {"login": "art@mail.ru", "password": "789"}

I need to read into an array of objects of type:

var userData = { login: params["login"], password: params["userpass"] }; 

I write to a file in JSON format:

  var userData = { login: params["login"], password: params["userpass"] }; var str = JSON.stringify(userData); fs.appendFile('txt/user.txt', str); 

But how back?

    2 answers 2

      var fs = require('fs'); var obj; fs.readFile('txt/user.txt', 'utf8', function (err, data) { if (err) throw err; obj = JSON.parse(data); }); 
    • What kind of object is obj ??? - bsuart
    • your json object - Roman Polshikov

    So-so decision, of course, but as long as there are no nested objects, it will work. And so, of course, it would be better to add a separator between the entries, for example, at least a newline ( \n ).

    Synchronous version:

     var userDataEntries = fs.readFileSync('txt/user.txt') .toString() .split(/(?={")/) .map(x => JSON.parse(x)); 

    Asynchronous:

     fs.readFile('txt/user.txt', (err, data) => { if (err){ // Обработка ошибок return; } var userData = data.toString().split(/(?={")/).map(x => JSON.parse(x)); }); 
    • Well, how then to record the username and password so that they can then be read and verified? Can it be more convenient without JSON? - bsuart
    • @ bsuart2017, in general, if new records are rarely added, you can simply overwrite the entire file, and then store the usual JSON array there. When adding, if not already loaded, read the usual JSON.parse(fs.readFileSync(…).toString()) , then .push({ … }) , then save with fs.writeFileSync(…) . - Surfin Bird