JSON Error when parsing “… has no method 'repl

2019-07-19 01:09发布

问题:

Let me preface this with the admission that I am a complete programming and javascript noob and that fact is the source of my trouble.

I'm trying to populate a large array of custom objects from a text file that I've saved to with json.stringify. When I grab the file contents and json.parse(them), I get the following error:

var backSlashRemoved = text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'
                            ^
TypeError: Object (contents of file) has no method 'replace'

The code that causes this error is:

fs.readFile('/savedcustomobjectarray', function (err, data) {
  var customobjectarray = json.parse(data);
});

I'm guessing I'm going about this all wrong. I saw some people mention serializers for this sort of thing, but I wanted to double check if that's what I needed (and maybe get some direction in how to use them in this context). It seems like the stringify output is fine, though, so I'm not sure why JSON can't just put humpty dumpty back together again. Any help would be greatly appreciated.

EDIT: The text.replace line is in /vendor/commonjs-utils/lib/json-ext.js, not my code. I assumed this was part of JSON. Perhaps I am wrong? Is there a different way to parse my object array through JSON?

回答1:

fs.readFile takes 2 or 3 arguments, when passing only the filename and a callback, then your callback function will get the following two arguments (err, data) where data is a raw buffer.

So the right way to do it would be:

fs.readFile('/savedcustomobjectarray', function (err, data) {
  var customobjectarray = JSON.parse(data.toString('utf8'));
});

data.toString takes the encoding as the first argument.

Alternitavley you could specify the encoding as the second argument to the fs.readFile and have it pass a string to the callback:

fs.readFile('/savedcustomobjectarray', 'utf8', function (err, data) {
  var customobjectarray = JSON.parse(data);
});

Node API docs is your best friend!