require is not defined javascript

24,564

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

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

Share:
24,564
JakeTheDane
Author by

JakeTheDane

Updated on August 23, 2021

Comments

  • JakeTheDane
    JakeTheDane over 2 years

    ****** 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 )