Web Frameworks

Student Validation (1)

<!-- create an Html form that contains the student registations and write and javascript to validate student first name and last name as is should not contains other than alphabets and age should be between 18 to 50 -->


<html>
    <head>
        <title>Student Form</title>

    </head>
    <body>
        <center>
            <h2>
                Student Registration Form
            </h2>
            <p>First Name : <input type="text" name="" id="fn"></p>
            <p>Last Name : <input type="text" name="" id="ln"></p>
            <p>Age : <input type="text"  id="numb"></p>
            <p id="demo"></p>
            <p>Address : <input type="text" id="add"></p>
            <button type="button" onclick="validate()">Click</button>
        </center>

        <script>
            function validate()
            {
                
                var x;
                //Get the value of the input feilds
                n1 = document.getElementById("fn").value;
                n2 = document.getElementById("ln").value;
                x = document.getElementById("numb").value;

                var letters = /^[A-Za-z]+$/;
             if((!n1.match(letters))||(!n2.match(letters)))
                {
                    alert("Invalid UserName");
                }
                else if( isNaN(x)||x<18||x>50)
                {
                    document.getElementById("demo").innerHTML = 'Incorrect Age';
                }else
                {
                    alert("Form Submitted")
                }
              
            }
     
        </script>
    </body>
</html>

Email Validation (3)

<html>
    <body>
        <center>
            <h2>Email Validation</h2>
   
        User Name : <input type="text" id="uname"> <br><br>
        Password : <input type="password" id="pass"> <br><br>
       Email : <input type="text" id="uemail"> <br><br>
       <button type="button"  onclick="ValidateEmail(uemail);">Click Here</button>
    </center>

    <script>
        function ValidateEmail(uemail)
        {
            if(!(uname.value == '') && !(pass.value=='') && !(uemail.value==''))
            {
                var mailFormat = /^\w+([\.-]?\w+)*@\w+([\.-]? \w+)*(\.\w{2,3})+ $/;
                if(uemail.value.match(mailFormat))
                {
                    alert("Login Success");
                    return true;
                }
                else {
                    alert("You have entered an Invalid Emails!");
                    uemail.focus();
                    return false;
                }
            }
                else {
                    alert("Field should not be empty")
                    return false;
                }
            }
       
    </script>
    </body>
</html>

Node JS Upper Case with server (4)

first run npm install upper-case

var http = require('http');
var uc = require('upper-case');

http.createServer(function (req,res) {
    res.writeHead(200, {'Content-Type':'text/html'});
    res.write(uc.upperCase("hello-word"));
    res.end;
}).listen(8050);
console.log("server running on 8080 port");

Run ” node test.js “


Using nodejs create a web page to read two file names from user and append contents of first file into second file (5)

const fs = require('fs');
console.log("\nFile Contents of file before append:", fs.readFileSync("example_file.txt", "utf8"));

fs.appendFile("example_file.txt", "World", (err) => { if (err) {
console.log(err);
}

else
{
console.log("\nFile Contents of file after append:", fs.readFileSync("example_file.txt", "utf8"));
}
});
const fs = require('fs');
console.log("\nFile Contents of file before append:", fs.readFileSync("example_file.txt", "utf8"));

fs.appendFile("example_file.txt", " - GeeksForGeeks",
{
encoding: "latin1", mode: 0o666, flag: "a" }, (err) => {

if (err)
{
console.log(err);
}

else {
console.log("\nFile Contents of file after append:", fs.readFileSync("example_file.txt", "utf8"))
}
});

Create a Node.js file that opens the rested file and returns the content to the client. if anything goes wrong, throw a 404 error (6)

var http = require('http');
var fs = require('fs');
http.createServer(function (req,res){
    fs.open('ex.txt',function(err, fd) {
        if(err){
            console.error(err);
            return res.end('404 not found');
        }
        else{
            console.log('file opened succesfully');
            fs.readFile('ex.txt', function(err,data){
           
                if(!err){
                    console.log('success');
                    res.end(data);
                    fs.close(fd);
                }
            });
        }
    })
}).listen(8080);

Create a Node.js file that writes an HTML form, with an upload field. (7)

var http = require('http');

http.createServer(function (req,res) {
    res.writeHead(200, {'Content-Type':'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="fileuplaod"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    res.end;
}).listen(8050);
console.log("server running on 8050 port");

Create a Node.js file that demonstrate create database and table in MySQL (8)


var mysql = require('mysql');
var con = mysql.createConnection(
{
host: "localhost", user: "root",
password: "",
});
con.connect(function(err)
{

if (err) throw err; console.log("Connected successfully ");
Con.$ry= ("CREATE DATABASE mydb", function (err, result)
{

if (err) throw err; console.log("Table is created");
});
});

Create a node.js file that Select all records from the “customers” table, and display the result object on console (9)

var mysql = require('mysql');
var con = mysql.createConnection(
{
host: "localhost", user: "yourusername",
password: "yourpassword", database: "mydb"
});
con.connect(function(err)
{

if (err) throw err;
con.$ry("SELECT * FROM customers", function (err, result)
{

if (err) throw err; console.log(result);
});
});


Create a node.js file that Insert Multiple Records in “student” table, and display the result object on console (10)

var mysql = require('mysql');
var con = mysql.createConnection({ host: "localhost",
user: "root", password: "root", database: "studentdb"
});
con.connect(function(err)
{

if (err) throw err; console.log("Connected!");
var sql = "INSERT INTO student (rollno,name, percentage) VALUES ?";

var values = [ [1,'abc', 77.6], [2,'def', 89.6], [3,'ghi', 91.6] ];

con.$ry(sql, [values], function (err, result)
{

if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});

con.$ry("SELECT * FROM student", function (err, result, fields) { if (err) throw err;
console.log(result);
});
});


Create a node.js file that Select all records from the “customers” table, and delete the specified record. (11)

var mysql = require('mysql');
var con = mysql.createConnection(
{
host: "localhost", user: "yourusername",
password: "yourpassword", database: "mydb"
});
con.connect(function(err)
{

if (err) throw err;
var sql = "DELETE FROM customers WHERE address = 'Mountain 21'";
con.$ry(sql, function (err, result)
{

if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});


Create a Simple Web Server using node js (12)

var http = require('http');
var server = http.createServer(function (req, res)
{
});
server.listen(5000);
console.log('Node.js web server at port 5000 is running..') 

write node js script to interact with the filesystem, and serve a web page from a file (14)

var http = require('http'); 
var fs = require('fs');
http.createServer (function(req, res) 
{ 
fs.readFile('Atharv.html',function(err,data) 
{ 
res.writeHead(200, ('Content-Type': 'text/html'}); 
res.write(data); 
return res.end();
 });
 }).listen(3000); 
console.log('server is running………’')


Myfile.html
Hello world…!!!
Welcome to the node.js

Write node js script to build Your Own Node.js Module. Use require (‘http’) module is a built-in Node module that invokes the functionality of the HTTP library to create a local server. Also use the export statement to make functions in your module available externally. Create a new text file to contain the functions in your module called, “modules.js” and add this function to return today’s date and time (15)

.module.js

function datetime()
{
    let dt = new Date();

    let date = ("0" + dt.getDate()).slice(-2);

    let month = ("0" + (dt.getMonth() + 1)).slice(-2);

    let year = dt.getFullYear();

    let hours = dt.getHours();

    let Minutes = dt.getMinutes();

    let seconds = dt.getSeconds();

    var output = year + "-" + month + "-" + date + " " + hours + ":" + Minutes + ":" + seconds;
    return output;


}
module.exports={datetime};

main.js

var http = require('http');

var dt = require('./modules');
http.createServer(function (req,res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    const result = dt.datetime();
    res.write('Current Date And time is');
    res.write('<br/>');
    res.write(result);
    res.end();
}).listen(5050);

Create a js file named main.js for event-driven applications. There should be a main loop that listens for events, and then triggers a callback function when one of those events is detected. (16)

var events = require('events'); 
var eventEmitter = new events.EventEmitter(); 
var connectHandler = function connected() 
{ 
console.log('connection successful.'); 
eventEmitter.emit('data_received'); 
} 
eventEmitter.on('connection', connectHandler); eventEmitter.on('data_received', function() 
{ 
console.log('data received successfully.'); 
}); 
eventEmitter.emit('connection'); 
console.log("Program Ended.") 

// Create.txt file Welcome to the world of computer science 

var fs = require("fs"); 
fs.readFile('input.txt', function (err, data) { 
if (err) 
{
 console.log(err.stack); return;
 } 
console.log(data.toString()); 
}); 
console.log("Program Ended");

Write a node js application that transfers a file as an attachment on the web and enables browsers to prompt the user to download file using express js. (17)

HTML

<html>
    <body bgcolor="orange">
        <form action="/file-data" method="post">
            <center>
                <table border="1">
                  <tr>
                    <td>select a file</td>
                    <td><input type="file" name="id"></td>
                  </tr>
                  <tr align="center">
                    <td colspan="2"><input type="submit" value="Download"></td>
                  </tr>
                </table>
            </center>
        </form>
    </body>
</html>

JS

var express = require ('express');
const fs = require('fs');
var app = express();
var PORT = 3000;

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',function(req,res){
    const files = fs.createReadStream('slip17.html');
    res.writeHead(200,{'content-type':'text/html'});
    files.pipe(res);
});

app.post('/file-data',function(req,res){
    var name = req.body.id;
    res.download(name);
});

app.listen(PORT,function(err){
    if (err) console.log(err);
    console.log("Server Listening PORT ",PORT);
});
Design a site like this with WordPress.com
Get started