Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

returned value from fs.readFileSync(...) can not be passed into JSON.parse #186

Closed
liucougar opened this issue Jun 20, 2010 · 1 comment
Closed

Comments

@liucougar
Copy link

run the following code:

var sys=require("sys"), fs=require("fs");
var content=fs.readFileSync("a.json");
sys.puts(JSON.parse(content));

file a.json (referenced above) can be any file containing any valid json (like: {"a":1} will do)

this is the output (nodejs 0.1.98):

/tp/selenium-hub/json.js:3
sys.puts(JSON.parse(content));
              ^

no detailed error message at all. It turns out the returned value from fs.readFileSync is not a string (typeof content is object), and JSON.parse expects a String as input

Workaround is to wrap the result of fs.readFileSync in a String, like this:

var sys=require("sys"), fs=require("fs");
var content=String(fs.readFileSync("a.json"));
sys.puts(JSON.parse(content));

this is a regression: the first code snippet worked fine with nodejs at:
commit 320d3e9
Fri May 14 11:15:31 2010 -0700

@liucougar
Copy link
Author

this is as design: readFileSync returns a buffer if no encoding is specified, this should be done like this:

var sys=require("sys"), fs=require("fs");
var content=fs.readFileSync("a.json", "utf8");
sys.puts(JSON.parse(content));

This issue was closed.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant