Javascript node js:为什么我不能在jason.js中异步写入,然后同步读取?
有人能帮我吗? 我的问题是:为什么我不能在jason.js中异步写入,然后同步读取 为了澄清我的问题,以下是我的代码:Javascript node js:为什么我不能在jason.js中异步写入,然后同步读取?,javascript,node.js,asynchronous,synchronization,Javascript,Node.js,Asynchronous,Synchronization,有人能帮我吗? 我的问题是:为什么我不能在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
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)
但当我让一切都同步时,它就工作了
非常感谢您希望在文件写入后尝试读取该文件。这意味着您必须在writeFile的回调函数中执行此操作
欢迎来到堆栈溢出 至于您的问题,您没有正确处理异步代码。您的读取应该在写入之后进行,因此您应该执行以下操作:
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);
});
您确定了解异步的含义吗?.writeFile函数调用在文件实际写入之前立即返回。@Pointy是的,同步代码以线性方式执行,而异步代码则不是这样。我可能错了,但这里他们说它不会立即返回,而是同步地将数据写入文件,这意味着它会立即返回。当操作完成时会调用回调。哦,是的,当然非常感谢,我现在就知道了:。非常感谢,我现在就知道了。非常感谢,非常欢迎。你能不能把这个标记为答案,这样其他人可能会受益?或者从上面选择@Nicks answer。看来他和我差不多同时回答了
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);
});