【问题标题】:node js : why can't I write asynchronously in jason.js and then read it synchronously?node js:为什么我不能在 jason.js 中异步写入,然后同步读取?
【发布时间】: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


【解决方案1】:

欢迎来到 Stack Overflow!

至于您的问题,您没有正确处理异步代码。您的阅读应该发生在您的写作之后,因此您应该执行以下操作:

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);
});

【讨论】:

  • 不客气。您能否将此标记为答案,以便其他人受益?或从上面选择@Nicks 答案。似乎他和我同时回答(差不多)
【解决方案2】:

您想在文件写入后尝试读取该文件。这意味着你必须在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);

});

【讨论】:

  • 非常感谢我现在明白了
猜你喜欢
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
  • 2015-12-29
  • 2014-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多