Node.js

 

  • Node.js is an open source server environment
  • Node.js is free
  • Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • Node.js uses JavaScript on the server
  • Node.js uses asynchronous programming!

  • Node.js can generate dynamic page content
  • Node.js can create, open, read, write, delete, and close files on the server
  • Node.js can collect form data
  • Node.js can add, delete, modify data in your database

What is a Node.js File?

  • Node.js files contain tasks that will be executed on certain events
  • A typical event is someone trying to access a port on the server
  • Node.js files must be initiated on the server before having any effect
  • Node.js files have extension ".js"

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type''text/html'});
  res.end('Hello World!');
}).listen(8080);


save as server1.js and in cmd type node server1.js
Open browser and type localhost:8080/  to see Hello World!

Create Your Own Modules


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

save as dateMod1.js

Include Your Own Module

Now you can include and use the module in any of your Node.js files.

Example

Use the module "dateMod1" in a Node.js file:


var http = require('http');
var dt = require('./dateMod1');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("The date and time are currently: " + dt.myDateTime());
  res.end();
}).listen(8080);

Read the Query String


demo_http_url.js


var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type''text/html'});
  res.write(req.url);
  res.end();
}).listen(8080);


http://localhost:8080/summer

Will produce this result:  /summer

http://localhost:8080/winter

Will produce this result:  /winter


File System Module

var fs = require('fs');

Common use for the File System module:

  • Read files
  • Create files
  • Update files
  • Delete files
  • Rename files

The fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created:

var fs = require('fs');
fs.writeFile('mynewfile3.txt''Hello content!'function (err) {
  if (err) throw err;
  console.log('Saved!');
});



Comments

Popular posts from this blog

AIDS Meanstack Sample questions

Express.js Registration form data 2 Server