The goal of this tutorial is to provide you with a thorough understanding of how to run JavaScript files using Node.js. By the end of this tutorial, you'll be able to execute JavaScript scripts from both the command line and within a Node.js application.
You will learn how to:
Prerequisites:
Before starting this tutorial, you should have Node.js installed on your machine. If you don't have it installed, you can download it from Node.js official website.
1. Running JavaScript files from the command line
To run a JavaScript file using Node.js from the command line, navigate to the directory containing your JavaScript file and use the following command:
node yourFile.js
Replace yourFile.js
with the name of your file.
2. Implementing Node.js scripts within a JavaScript file
You can also run scripts within a Node.js application by creating a JavaScript file, writing Node.js code in it, and then running the file using the Node.js command-line interface.
Best practices and tips:
node -v
before running any scripts. This ensures that Node.js is properly installed and you're using the required version.Example 1: Running a simple JavaScript file
Create a JavaScript file named helloWorld.js
and write the following code in it:
console.log('Hello, World!');
To run the file, open your command line, navigate to the directory where your file is located, and type:
node helloWorld.js
Expected output:
Hello, World!
Example 2: Implementing a Node.js script in a JavaScript file
Create a JavaScript file named server.js
:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!\n');
}).listen(8080);
console.log('Server running at http://localhost:8080/');
To run the file, open your command line, navigate to the directory containing the file, and type:
node server.js
In your browser, go to http://localhost:8080/
to see the result.
In this tutorial, you've learned how to execute JavaScript files using Node.js both from the command line and within a Node.js application. The next step would be to explore more advanced Node.js topics, such as working with file systems, creating servers, and using databases.
For further reading, check out the Node.js Documentation.
/about
should return "About me", /contact
should return "Contact me").Remember, the best way to learn is by doing. Keep practicing and experimenting with different scripts and functionalities in Node.js.