Node.js is a JavaScript runtime built on the V8 JavaScript engine. It allows you to run JavaScript code on the server side.
-
Advanced
- Visit the Node.js official website to download and install Node.js on your machine.
-
Open a text editor and create a file named
app.js
. -
Add the following code to print "Hello, Node.js!" to the console:
console.log("Hello, Node.js!");
-
Open a terminal and navigate to the directory containing
app.js
. -
Run the following command to execute your Node.js script:
node app.js
-
You should see the output: "Hello, Node.js!".
-
npm is the package manager for Node.js. It allows you to install and manage packages (libraries) for your Node.js projects.
-
Check the installed npm version:
npm -v
-
Initialize a new
package.json
file for your project:npm init
Follow the prompts to configure your package.
- Create a new file named
server.js
. - Add the following code to create a basic HTTP server:
This is a most basic GET API, which we will use in almost all of the modules to describe their functionality.
// # import default `http` module from node.js
const http = require("node:http");
// # create a server instance, which is listing port 3000.
http
.createServer((req, res) => {
// # Creating response header with 200 status code.
res.writeHead(200, { "Content-Type": "text" });
// # Sent this string as API response
res.end("Basic GET API");
})
.listen(3000, () => {
// # Listing port 3000
console.log(`Listening port 3000`);
});
// # You can check this API on your browser 3000 port.