Experimenting with Node.js - Part 01

Published on
hourglass-not-done2 mins read
eye––– views

Basic server

var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
// res.writeHead(200, {'Content-Type': 'text/plain'});
// res.write("The date and time are currently: " + dt.myDateTime());
// res.end('\nHello World!');
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end('<br>Hello World!');
}).listen(8080);
console.log('This example is different!');
console.log('The result is displayed in the Command Line Interface');

Module

exports.myDateTime = function () {
return Date();
};

Query Parse URL

var http = require('http');
var url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
res.end(txt);
}).listen(8080);

File operations

// Using ES modules with fs/promises for proper await support
import { writeFile, appendFile, rename, unlink } from 'fs/promises';
// Async function to execute file operations sequentially
async function runFileOperations() {
try {
// Create first file
await writeFile('mynewfile3.txt', 'Hello content!');
console.log('Saved mynewfile3.txt!');
// Create second file
await writeFile('mynewfile1.txt', 'This is my text');
console.log('Created mynewfile1.txt!');
// Create third file
await writeFile('mynewfile2.txt', 'This is my text');
console.log('Created mynewfile2.txt!');
// Append content to file
await appendFile('mynewfile1.txt', ' This is my text.');
console.log('Updated mynewfile1.txt!');
// Rename file
await rename('mynewfile1.txt', 'myrenamedfile.txt');
console.log('Renamed mynewfile1.txt to myrenamedfile.txt!');
// Delete file
await unlink('mynewfile2.txt');
console.log('Deleted mynewfile2.txt!');
// Replace content in remaining file
await writeFile('mynewfile3.txt', 'This is my text');
console.log('Replaced content in mynewfile3.txt!');
} catch (error) {
console.error('Error during file operations:', error);
}
}
// Execute all operations
runFileOperations();

File Server

<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);

localhost:8080/summer.html