I am tyring to get node.js working and when I call a ‘require’, I get the following error Uncaught ReferenceError: require is not defined
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Hi there,
This error usually occurs when trying to use Node.js’s require() function in a context where it isn’t defined. This is common when you try to use require() in client-side JavaScript, which runs in a web browser.
Web browsers don’t support the require() function natively because it is part of Node.js’s module system (CommonJS), not part of standard JavaScript. To use modules in client-side JavaScript, you would generally use the ES6 import statement. However, this assumes that the script you’re importing is an ES6 module, and it must be served from a web server due to CORS (Cross-Origin Resource Sharing) policies in browsers.
If you’re trying to use a Node.js library in client-side code, you will often need to use a tool like Browserify or Webpack. These tools bundle your code and its dependencies into a single JavaScript file that can be included in your HTML.
If you are indeed trying to use Node.js and the error persists, it could be due to several reasons:
The script is not running in a Node.js environment. Make sure you’re running your script with Node.js, e.g. node your_script.js in the command line.
The module you’re trying to require is not installed. If you’re trying to require a third-party module, make sure it’s installed using npm install module_name.
The path to the module is incorrect. If you’re trying to require a local file, make sure the path to the file is correct. For example, if you’re in the same directory as the file, the require statement would be require('./filename').
If none of these solutions work, feel free to share more details about your exact setup!
Best,
Bobby
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.