run node server locally code example

Example 1: Create a server which serves at port 3000 and with node.js command prompt

// app.js

const http = require('http');

// Create an instance of the http server to handle HTTP requests
let app = http.createServer((req, res) => {
    // Set a response type of plain text for the response
    res.writeHead(200, {'Content-Type': 'text/plain'});

    // Send back a response and end the connection
    res.end('Hello World!\n');
});

// Start the server on port 3000
app.listen(3000, '127.0.0.1');
console.log('Node server running on port 3000');

//console
$ node app.js // runs it
//to open it in ur browser, go to http://localhost:3000.

Example 2: how to create server.js file

npm install server

Example 3: run node app locally

// Run this command in your terminal to start your node application.
// Replace the tag with your applications main file name (ex index.js, main.js etc). 
// Add alternative a relative or absolute path before the name.

node <filename>.js

Tags:

Php Example