json - Node fs.writeFileSync 错误

标签 json node.js

我目前正在学习 Node.JS 类(class),我们正在使用 fs.writeFileSync() 通过终端读取、写入、保存和编辑用户的输入数据。它对于几句话长的文本效果很好,但对于任何更大的文本, Node 终端 (>) 开始运行,而不是运行代码。 Image1 Image2

我对 Node.js 有基本的了解,但不明白为什么这种情况不断发生。 非常感谢任何帮助。谢谢。

下面的代码,

const fs = require('fs');

var originalNote = {
    title: process.argv[2],
    body: process.argv[3],
};

var originalNoteString = JSON.stringify(originalNote);

fs.writeFileSync('Notes.json', originalNoteString);

var noteString = fs.readFileSync('Notes.json');

var Note = JSON.parse(noteString);

console.log(typeof (Note));
console.log(originalNoteString);
console.log(Note.title);
  • 终端输出1-

Viveks-MacBook-Pro:playground Vivek$ node JSON.js 'Lorem Ipsum' 'ldfdfefnhebfhbfhrbfherbfhrbfhrefocalStorage fefef fede'

object

{"title":"Lorem Ipsum","body":"ldfdfefnhebfhbfhrbfherbfhrbfhrefocalStorage fefef fede"}

  • 终端输出2-

Viveks-MacBook-Pro:playground Vivek$ node JSON.js 'Lorem Ipsum' 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a typespecimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum'

'>'

最佳答案

基本问题在于第二个参数中发送的数据。

如果您查看数据,就会发现其中包含industry's一词,其中包含单引号

这导致第二个参数被截断。

如果您将第二个参数放在双引号中,您的代码应该可以正常工作。

如果可能的话,您还可以使用转义字符来忽略数据中的单引号。

我希望这有帮助:)

关于json - Node fs.writeFileSync 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50945777/

相关文章:

node.js - 通过服务器端脚本使用 node-ncurses 客户端?

node.js - 检查node.js中分配的最大内存大小

ios - AFNetworkActivirty 记录器 swift 3.0 xcode 8 不记录任何内容

javascript - ES6 动态导入和实例化类

c# - 安卓 JSON 安全

ios - 使用 Alamofire 解析 Codable 响应

node.js - 像 CakePHP 一样在 Node.js 中制作 token ?

Javascript 将一个数组对象分配给另一个数组

javascript - 将 javascript 日期转换为 json 日期格式

mysql - 选择MySQL表中JSON类型值的计数