0

I use this code in my .js file which is part of web site that is used via npm global http-server:

function getParsedStorage() {
  let fs = require('fs');
  return JSON.parse(fs.readFileSync('./../manager-data.json', 'utf8'));
}

and get errors:

jQuery.Deferred exception: Can't find variable: require (2) (exceptionHook — jquery.min.js:2:31584)

ReferenceError: Can't find variable: require (jquery.min.js:2:31697)

I've installed file-system package with npm install file-system --save but that didn't change anything.

1 Answer 1

1

It looks to me like you're attempting to make use of Node.js's require function from within a web browser without using a module system that provides a compatible require method.

Without additional information I can't be certain, however my advice would be to investigate a module loader like Require.js, SystemJS or Browserify which should all enable you to make use of this syntax in your module.

That being said, for the use case you're describing (accessing a JSON file from a website) you may be better served using a simple XHRHttpRequest or the fetch API.

The following is an example which makes use of the fetch API to return the parsed JSON file content.

// Returns a Promise that resolves to the parsed storage data
// NOTE: Lacks any error handling
function getParsedStorage() {
  return fetch("../manager-data.json").then(response => response.json())
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that was a moment of coding madness and despair. Thank you for your answer. Now I've learned a little about node.js and do my server part using it.

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.