6

****** EDIT *******

I do realize the mistake now, i was running my script in my terminal when i was testing my require.

****** OLD ****

The answer might all ready be here on the page, but i have not been able to find it, the general answers i see is that i cannot use "require" client sided.

The thing is the script i am trying to run works perfectly on my school laptop. But it doesnt want to run on my on Desktop at home.

I am trying to run a script where i want to require like this. "var fs = require('fs');"

But the console in my browser just gives me this error ( ReferenceError: require is not )

I am using Visual Studio Code, with Node.js.

I have a basic index.html file which uses 1 script.js file. Nothing else is being used for it.

A link for my files should you want to take a look ( https://drive.google.com/file/d/1VgEmwtcHkURFT1WmPOnEKr_OHLT_SY78/view?usp=sharing )

4 Answers 4

3

I am using Visual Studio Code, with Node.js.

I have a basic index.html file which uses 1 script.js file.

So you have two sets of JS.

  1. JS that runs in Node.js
  2. JS that runs in the browser (delivered via index.html)

var fs = require('fs'); is very much in the former category. require is a built-in in Node.js. fs is a core library of Node.js.

You are trying to run it in the browser, where it isn't supported and does not work. You need to run it in Node.js.

i see is that i cannot use "require" client sided.

There are browser-side implementations of require and tools (like Webpack) which will bundle modules into a browser compatible file, but neither of those approaches will help you here because fs itself depends on Node.js.

Sign up to request clarification or add additional context in comments.

1 Comment

Omg i am really stupid. And a bit tired indeed it seems. I get the mistake now, when i was testing solely the script i was running it in my terminal, instead of through the browser.
1

require() is not standard JavaScript, it's built into NodeJS to load modules.

Try using Express or similar to run a simple web server and it should work. Right now it's not working from home because it's not being compiled by the Node engine.

1 Comment

yes the mistake just hit me in the face, when i was testing my require on the school laptop, i was doing it through my terminal
1

require() it's not an internal function of javascript in the front-end, you're going to need to import some library that realizes this for you, as for example require.js or browserify. Otherwise fs is only supported in NodeJS you need to run in the server not in the browser.

Comments

1

this helped me, check your package.json for type:"module" and remove it.

Comments

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.