简体   繁体   English

Javascript同步写入文件和读取文件

[英]Javascript synchronous writing to a file and reading from a file

I have a need to store data in variable, store whole variable to a file and then read it from a file.我需要将数据存储在变量中,将整个变量存储到文件中,然后从文件中读取它。

How to achieve that with Java script?如何使用 Java 脚本实现这一目标?

Tried with:尝试过:

fs.writeFileSync('/tmp/data.txt', JSON.stringify(objectData));
fs.readFile('/tmp/data.txt', (err, data) => {
  if (err) throw err;
  console.log(data);
});

But second part is executing before file write finishes giving either corrupted data or partial one.但是第二部分是在文件写入完成提供损坏的数据或部分数据之前执行的。

How to achieve above scenario?如何实现上述场景?

I think in your case it's better if you use fs.writeFile as described here , to ensure if your write has been done and then read your file:我认为在您的情况下,最好使用 fs.writeFile 如here所述,以确保您的写入已完成,然后读取您的文件:

fs.writeFile('/tmp/data.txt', JSON.stringify(objectData), (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
fs.readFile('/tmp/data.txt', (err, data) => {
  if (err) throw err;
  console.log(data);
});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM