. Advertisement .
..3..
. Advertisement .
..4..
Since its launch, Node.js has received mixed reactions, with praise and criticism. It seems the controversy is still ongoing. But in these controversies, we realize that every programming language and every platform is criticized for certain issues surrounding the way we use the platform.
Although Node.js makes it harder for developers to write secure code or write high-quality concurrent code, the platform is well known for building powerful and modern web services. These web services scale well and have proven stable, maintaining their position on the Internet.
However, like any other platform, Node.js is vulnerable to programming problems. Some issues degrade performance, others make Node.js unusable despite your best efforts. In this article, we will continue to throw a new error in Node.js, it’s “require is not defined?” and how to handle it.
What is “require is not defined?”
You ran a program like below in the app.js file:
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Am I really running a server?!');
}).listen(8080, '127.0.0.1');
console.log('running server!');
The above program, when opened in node app.js, it still works normally and displays the line “running server!”. However, when running with the browser, there was an error “Uncaught ReferenceError: require is not defined”.
Solution
You should remember, the results returned when running a program in node are different than when you run them in a browser. Because depending on both use Javascript, but the conditions for the program to run in each side are different (this applies to V8 in Chrome as well).
Node.js uses CommonJS to implement the module system, and require is the command to require the use of a module in a specified file. The basic function of require is that it will read a file, execute it, and then return the exported objects.
In simple terms, In NodeJs, you can control the development environment, and you can choose the version for NodeJs. In the Browser environment, you do not have many options to use.
With NodeJs you can use “require” keyword to use modules but not in Browser. When you use “require” in the Browser, the browser will give an error.
Conclusion
Above is the answer to the error “require is not defined?” in Node.js. In addition, we also show the differences between Node and Browser that everyone needs to know. In order to avoid unwanted errors, you should know these issues well. Hope this article helps those who are just starting to learn programming. If you have any suggestions or questions, please feel free to comment below. Thanks for reading!
→ Read more: Fix the error “Uncaught referenceerror: require is not defined” in Javascript
Leave a comment