In: Computer Science
Using Node.js as a Webserver
1. How do you modify a webserver.js code to include your name and date? Please include code.
2. Create a MongoDB database for the following group that includes member names and contact information and Include code: Gourp member exapmples: Pete 912-555-6666; Sam 912-111-3333; Mary 678-111-1111; and April 912-690-1111
1)
var http = require('http');
myDateTime = function () {
return Date();
};
//create a webserver.js:
http.createServer(function (req, res) {
res.write('Name: Sam '); //write a response to the client
res.write("\nThe date is " + myDateTime());
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
========================================================
2)
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb"); //Databasename
var myobj = [
{ name: 'Pete', contact: '912-555-6666'},
{ name: 'Sam', contact: '912-111-3333'},
{ name: 'Marry', contact: '678-111-1111'},
{ name: 'April', contact: '912-690-1111'}
];
//it creates collection f not created else insert into existing one
dbo.collection("members").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db.close();
});
});
----------------------------------------------------
Output:
Number of documents inserted: 4