5

I want to read data from a file and add it to an Object stored in memory. The data in the file text.txt looks roughly like this:

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

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

I'm trying to set it to an empty Object like so:

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

However, when I log text to the console, it comes out looking like this:

{ 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' }

Apparently, it's reading data as a key. What I really want, though, is something more like so:

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

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

Any advice here would be much appreciated.

Christopher Ronning
  • 1,875
  • 3
  • 19
  • 28
  • Real simple: just use `JSON.parse(data);`. See duplicate: [Using Node.JS, how do I read a JSON object into (server) memory?](http://stackoverflow.com/questions/10011011/using-node-js-how-do-i-read-a-json-object-into-server-memory) – paulsm4 Mar 13 '16 at 00:06
  • I tried that solution. When I do that I get `Syntax Error: Unexpected token O` – Christopher Ronning Mar 13 '16 at 00:09
  • It just occured to me that a possible solution to that syntax error is to wrap everything in the text.txt file inside some `{}` curly brackets. That creates some difficulties for me; is there any way to avoid that? – Christopher Ronning Mar 13 '16 at 00:14
  • 2
    Q: `Syntax Error: Unexpected token O`. A: Then your Json file is illegal. SUGGESTION: make sure you've got `{...}` delimiting your outermost "data" node. The answer to the question you posted is "use JSON.parse()". The answer to your syntax error is "fix your JSON file". – paulsm4 Mar 13 '16 at 00:16

2 Answers2

4

If you are using a newer version of Node, then you have support for ES6.

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

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

That's why you end up with an object that has the key data and the value is a string version of what was found in the file. Instead, just use JSON.parse on the data parameter (which is a string) and it'll convert it to an Object, which you can store in text. Like this

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

You'll also need to make the file valid json. Which means keys need quotes around them as do String values.

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

  "Two": {
    "title": "Two" ,
    "contributor": "Chris" ,
    "summary": "blah blah i'm a blah" ,
    "comments": ""
  }
}
Spidy
  • 39,723
  • 15
  • 65
  • 83
  • See my comment on the question. – Christopher Ronning Mar 13 '16 at 00:10
  • Oops sorry, ya updated my answer with the other issues – Spidy Mar 13 '16 at 00:18
  • Urgh.... Welp, that's probably the best I'm gonna get. Fair solution. I'm gonna leave this open to see if anybody chimes in with a way to do this without wrapping the whole thing in brackets. – Christopher Ronning Mar 13 '16 at 00:19
  • You could load it as a Javascript file using require() but you'd need to add a line for exporting – Spidy Mar 13 '16 at 00:22
  • Or use a better extended file system like fs-extra or node-jsonfile, but you'll notice they just do it for you: https://github.com/jprichardson/node-jsonfile/blob/master/index.js#L14 – Spidy Mar 13 '16 at 00:30
  • Well, wrapping the whole thing in brackets is way easier than I thought -- `fs.writeFile("./public/text.txt", JSON.stringify(text), function(error) { if (error) throw error; } });` That solves my whole problem with this solution. – Christopher Ronning Mar 13 '16 at 00:39
0

What you are trying to do is use eval, which is the only way if you really don't want to edit the file to be valid JSON or to export an object as @Spidy suggested. Just be sure the file is valid JavaScript, because the example you gave had

summary: 'blah blah i'm a blah'

but you need to escape i'm like i\'m.

var fs = require('fs');
var text = {};
fs.readFile('./public/text.txt', 'utf-8', function (error, data) {
  eval(`text = {${data}}`);
//eval('text = {' + data + '}');
});

But I wouldn't necessarily recommend that because that allows arbitrary javascript to get executed. Depending on how the data in the file gets there it would be a huge security risk.

janka102
  • 979
  • 1
  • 8
  • 16