1

I'm trying to do a function with JS and nodejs to create a .json file with my MongoDB data in it.

But when I run my function my console show me

Uncaught TypeError: Cannot read property 'prototype' of undefined.

I've done some research and my console that writeJsonFile's value is an object with no value, I don't know if it's the cause of my problem

json(event){ 
 count = Subs.find({}).count();
  var json;
  var obj;
  Subs.find({}).forEach(function (div) {
    var sub_type = div.type;
    var sub_TO = div.text;
    var man = div.topic;
    obj = {[man]: []};
    obj[man].push({"type": sub_type, "TO": sub_TO});
    json = JSON.stringify(obj);
    const writeJsonFile = require('write-json-file');

    writeJsonFile('foo.json', {foo: true}).then(() => {
      console.log('done');
    });
    console.log(json);
  });
}
5
  • On what line do you get this error? And do you still get the error if you remove all code above the json writing part? Commented Nov 27, 2017 at 15:07
  • Where do you get this error ? In the writeJsonFile function whose code you don't show ? Commented Nov 27, 2017 at 15:07
  • @Jerodev the error came at the line const writeJsonFile = require('write-json-file'); and if i remove the code above i still have the problem Commented Nov 27, 2017 at 15:16
  • Is write-json-file a third party module, or something you've written in the same folder as that JS code? Commented Nov 27, 2017 at 15:22
  • @Andy write-json-fileis a npm install module that i found here [link] (github.com/sindresorhus/…) Commented Nov 27, 2017 at 15:27

1 Answer 1

3

Better you use fs module of nodejs. No need to install it.

Here simple example of writing data to JSON file.

const fs = require('fs');
json = {
    one: 1,
    two: 2
}
json = JSON.stringify(json);
fs.writeFile('./foo.json', json, (err) => {
    if (!err) {
        console.log('done');
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

I've install nodejs and copy paste your code but i have an error fs.writeFile is not a function (sorry if i'm bad i've never use it)
the last one 9.2.0
the function will be in a react app so i use meteor to run my react app
make one file test.js copy paste my code in that file and do node test.js. Is it working or not?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.