Search code examples
javascriptjsonrequirejsstringify

Javascript app: require is not defined


I have an array and I want to create a .json to store the array in it. This is what I have, but i receive require is not defined. I know it has something to do with NodeJS, but I dont know what I should do.

let answersString = JSON.stringify(answersArray);
const fs = require('fs');

fs.writeFileSync("answers.json", answersString);

Thanks!

EDIT: Now I know this was a pretty dumb question, sorry. In the meantime I learned about node, bundling, testing etc.


Solution

  • You're using the code in client, and require() does not exists in javascript browser-side (nodeJS is server side...).

    My proposal would be to send file to server side where you will have fs and do the work there.

    Check this answer