how to run node code example
Example 1: run node js
node name_app.js
Example 2: SERVER PORT NODE.JS
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Example 3: node run command
// Run a command asynchronously
const { spawn } = require('child_process');
const dir = spawn('cmd', ['/c', 'dir']);
dir.stdout.on('data', data => console.log(`Stdout: ${data}`));
dir.stderr.on('data', data => console.log(`Stderr: ${data}`));
dir.on('close', code => console.log(`Exit code: ${code}`));
// Run a command synchronously
const { spawnSync } = require( 'child_process' );
const dir = spawnSync('cmd', ['/c', 'dir']);
console.log(`Stdout: ${dir.stdout.toString()}`);
console.log(`Stderr: ${dir.stderr.toString()}`);
Example 4: create node project
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.status(200).send('Hello World!');
});
var port = process.env.PORT || 3000;
var server = app.listen(port, function() {
console.log('Express server listening on port ' + port);
});
open cmd run server.js
"node server.js"
log:Express server listening on port 3000
& then
open link "http://localhost:3000/" in your browser and show result.
Example 5: node command
> node
Welcome to Node.js <version>.
>'type in javascript'
Example 6: 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