简体   繁体   中英

Node: TypeError: Cannot read property 'on' of undefined

I'm trying to parse a JSON file using Node JS, but the file doesn't seem to be read properly. I keep getting this error:

request.on("error", function(error){
       ^

TypeError: Cannot read property 'on' of undefined
    at Object.<anonymous> (/Users/jaeeunlee/Downloads/takehome_test-master/prediction.js:31:8)
    at Module._compile (module.js:410:26)
    at Object.Module._extensions..js (module.js:417:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:442:10)
    at startup (node.js:136:18)
    at node.js:966:3

My Node JS file:

var fs = require("fs");

var request = fs.readFile("blog_data.json", 'utf8', function(response){
   var body = "";
   console.log(response.statusCode);
   response.on("data", function(chunk) {
        body += chunk;
   });
   response.on("end", function(){
        // var profile = JSON.parse(body);
        // console.dir(profile);
   })
});


request.on("error", function(error){
    console.error(error.message);
})

The callback to readFile takes two arguments: the error and the data. It reads the data all at once. You are trying to use this like http.request but it works very differently.

const fs = require("fs");

fs.readFile("blog_data.json", 'utf8', (err, data) => {
   if (err) return console.error(err.message);
   console.dir(JSON.parse(data));
});

This is not an HTTP request. There is no statusCode , etc. You are just reading a file.

Also, node.js has the ability to import JSON as an object using require :

console.dir(require("./blog_data.json"));

You may mean fs.createReadStream instead of readFile . See https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options .

Otherwise, see https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback . Use it like this:

fs.readFile('blog_data.json', function(err, data) {
  ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM