请有人可以帮助我吗? 我的问题是:为什么我不能在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)
但是当我使所有内容同步时,它就会起作用。
非常感谢
答案 0 :(得分:0)
您要尝试在文件写入后读取 。这意味着您必须在writeFile
的回调函数中执行此操作。
//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);
});
答案 1 :(得分:0)
欢迎堆栈溢出!
关于您的问题,您没有正确处理异步代码。您的读应该在写后发生,所以您应该执行以下操作:
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);
});