【发布时间】:2019-06-12 19:56:36
【问题描述】:
请问有人可以帮我吗? 我的问题是:为什么我不能在 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)
但是当我让一切同步时,它就可以工作了。
非常感谢
【问题讨论】:
-
您确定您了解“异步”的含义吗?
.writeFile()函数调用在实际写入文件之前立即返回。 -
@Pointy 是的,同步代码以线性方式执行,而异步代码则不然。
-
nodejs.org/dist/latest-v11.x/docs/api/… 我可能错了,但这里他们说它不会立即返回
-
“异步将数据写入文件”——这意味着它会立即返回。操作完成时调用回调。
-
哦,是的,当然非常感谢,我现在明白了:)。
标签: javascript node.js asynchronous synchronization