Пожалуйста, кто-нибудь может мне помочь с этим?
мой вопрос: почему я не могу писать асинхронно в jason.js, а затем читать его синхронно?
Чтобы прояснить мой вопрос, вот мой код:
const fs = require('fs');
var originalNote = {
title: 'todo list',
body : `that's my secret`
};
var stringNote = JSON.stringify(originalNote);
//here I write asynchronously into my note.json file
fs.writeFile('note.json',stringNote, () => {
console.log('hey there');
});
//here I read synchronously from the note.json file
var file = fs.readFileSync('./note.json');
var note = JSON.parse(file);
когда я делаю это, я получаю следующую ошибку:
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.<anonymous> (/Users/yosra/Desktop/notes-node/playground/json.js:31:18)
at Module._compile (internal/modules/cjs/loader.js:721:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
at executeUserCode (internal/bootstrap/node.js:342:17)
at startExecution (internal/bootstrap/node.js:276:5)
но когда я делаю все синхронно, это работает.
Большое спасибо