If JavaScript files are loaded and executed in the browser how does the server know when the file is a node js file, therefore to execute on the server?
03 Answers
JavaScript is a language. node.js is not a language but an "environement/set of software" that runs normal JavaScript.
All browsers have JavaScript engines that run the JavaScript of web pages (Spidermonkey for Firefox, V8 for Chrome).
Node.js is simply the V8 engine bundled with some libraries to do I/O and networking, so that you can use JavaScript outside of the browser (e.g, to create backend services).
1I think concrete examples work better than conceptual explanations when there's confusion in the air. So, take this example:
You have a Node.js script called "hello.js" (in JavaScript, of course) that just prints "Hello World!" in the console and exits. You can run this script by typing node hello.js. It will just print the message and exit.
You have another Node.js script called "server.js" that implements an HTTP server (aka web server) that listens on port 3000. This server serves static files from a directory called "static". There are two files in this folder: "index.html" and "app.js". These are files for a web site (and app.js is in JavaScript, of course). You run this script by typing node server.js. It will spin up the HTTP server and start waiting for client requests.
While the HTTP server script is running, you visit "" to hit the very web server that you started above. The server knows how to serve off static files and knows that it should serve index.html by default. Your browser loads index.html, processes it and understands that it should also go back and request the app.js file (because of the <script> tag in index.html). When app.js is loaded by the browser, the browser runs it. The Node.js server doesn't care about anything but serving it as just another static file.
Both web browsers and nodejs run javascript scripts. The main difference is that NodeJS is a server side framework, and executes javascript code in a server and not in the environment of a web browser (client side).
There isn't any concept like nodejs file. There are only javascriprt scripts that can be run on client (by the help of the JavaScript engine that is built in a web browser, like V8 for chrome) or in the server (by the help in this case of NodeJS. By the way, if I am not wrong the JavaScript engine that NodeJS uses is the V8, google's JavaScript engine.)
0