javascript - 将 Node.js 对象设置为从文件读取的数据

标签 javascript node.js object readfile fs

我想从文件中读取数据并将其添加到存储在内存中的对象中。文件 text.txt 中的数据大致如下所示:

One: {title: 'One' ,
contributor: 'Fred',
summary: 'blah' ,
comments: 'words' },

Two: {title: 'Two' ,
contributor: 'Chris' ,
summary: 'blah blah i'm a blah' ,
comments: '' },

我试图将它设置为一个空对象,如下所示:

var fs = require('fs');
var text = Object.create(null);
fs.readFile("./public/text.txt", "utf-8", function(error, data) {
  text = { data };
});

但是,当我将 text 记录到控制台时,它看起来像这样:

{ data: 'One: {title: \'One\' ,\ncontributor: \'Fred\',\nsummary: \'blah\' ,\ncomments: \'words\' },\n    \nTwo: {title: \'Two\' ,\ncontributor: \'Chris\' ,\nsummary: \'blah blah i\'m a blah\' ,\ncomments: \'\' },\n\n' }

显然,它正在读取 data 作为键。不过,我真正想要的是更像这样的东西:

{
  One: {title: 'One' ,
  contributor: 'Fred',
  summary: 'blah' ,
  comments: 'words' },

  Two: {title: 'Two' ,
  contributor: 'Chris' ,
  summary: 'blah blah i'm a blah' ,
  comments: '' },
}

如有任何建议,我们将不胜感激。

最佳答案

如果您使用的是较新版本的 Node,那么您将支持 ES6。

// So your code 
`text = { data }` 

// is actually a shortcut for 
`text = { data: data }`

这就是为什么您最终会得到一个对象,该对象具有关键数据并且该值是在文件中找到的内容的字符串版本。相反,只需对数据参数(它是一个字符串)使用 JSON.parse,它会将其转换为一个对象,您可以将其存储在文本中。像这样

var fs = require('fs');
var text = Object.create(null);
fs.readFile("./public/text.txt", "utf-8", function(error, data) {
  text = JSON.parse(data);
});

您还需要使文件成为有效的 json。这意味着键和字符串值一样需要引号。

{
  "One": {
    "title": "One" ,
    "contributor": "Fred",
    "summary": "blah" ,
    "comments": "words"
  },

  "Two": {
    "title": "Two" ,
    "contributor": "Chris" ,
    "summary": "blah blah i'm a blah" ,
    "comments": ""
  }
}

关于javascript - 将 Node.js 对象设置为从文件读取的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35964874/

相关文章:

javascript - 分区 : Completely rendered indicator event

javascript - l20n:服务器端 Node resolveValues错误

node.js - Node REPL "on exit"事件

javascript - 使用 Angular js 检测 JS 对象的变化

json - 类型错误 : <object> is not JSON serializable

javascript - Nivo slider 加载问题?

javascript - 如何使用javascript导出带有输入字段的表格?

javascript - 使用 JQuery 和 JavaScript 将事件绑定(bind)到单页应用程序的 DOM

node.js - 错误 : Procfile does not exist, 和启动 Web 进程时出现问题

flash - Actionscript 对象的属性数