NODE.JS:WEB module, File system

Source: Internet
Author: User
Tags create directory readfile

one, the Web module

Web servers generally refer to Web servers, which are programs that reside on some type of computer on the Internet, and the basic function of Web servers is to provide web information browsing services. It only supports HTTP protocols, HTML document formats, and URLs, in conjunction with the client's Web browser. Most Web servers support the server-side scripting language (PHP, Python, Ruby) and so on, and get the data from the database in a scripting language and return the results to the client browser. At present, the most mainstream three Web servers are Apache, Nginx, IIS.

Web Application Architecture:

    • Client-clients, commonly referred to as browsers, can request data from the server via the HTTP protocol.

    • Server -a server-side, generally referred to as the Web servers, can receive client requests and send response data to the client.

    • Business-service layer, which handles applications through Web servers, such as interacting with databases, logical operations, calling external programs, and so on.

    • Data-the database layer, which is typically made up of databases.

1. Create a WEB server using Node

node. JS provides HTTP modules, which are used primarily to build HTTP servers and clients, using HTTP server or client features that must invoke the HTTP module with the following code:

var http = require ('http');

Demonstrates one of the most basic HTTP server architectures (using 8080 ports) to create a server.js file

varHTTP = require ('http');varFS = require ('FS');varurl = require ('URL'); //Creating a serverHttp.createserver (function (request, response) {//parse the request, including the file name   varpathname =Url.parse (request.url). Pathname; //the file name of the output requestConsole.log ("Request for"+ Pathname +"received."); //read the requested file contents from the file systemFs.readfile (Pathname.substr (1), function (err, data) {if(Err) {Console.log (err); //HTTP Status code: 404:not FOUND//Content Type:text/plainResponse.writehead (404, {'Content-type':'text/html'}); }Else{                      //HTTP Status code: 200:ok//Content Type:text/plainResponse.writehead ( $, {'Content-type':'text/html'}); //Response File ContentsResponse.Write (Data.tostring ()); }      //Send response DataResponse.End ();   }); }). Listen (8080); //the console will output the following informationConsole.log ('Server running at http://127.0.0.1:8080/');

File contents can be accessed after the file is added

2, through the form of configuration

varHTTP = require ('http'); //options for the requestvarOptions ={host:'localhost', Port:'8080', Path:'/index.html'  }; //callback function for handling responsesvarcallback =function (response) {//keep updating your data   varBODY ="'; Response.on ('Data', function (data) {body+=data;      }); Response.on ('End', function () {//Data Reception CompleteConsole.log (body); });}//sending requests to the servervarreq =http.request (options, callback); Req.end ();
ii. File System

node. JS provides a set of UNIX-like (POSIX)-compliant file manipulation APIs. The Node import file System module (FS) syntax is as follows:

var fs = require ("fs")  

The methods in the node. js file System (FS module) module have asynchronous and synchronous versions, such as functions that read the contents of the file with asynchronous Fs.readfile () and synchronous Fs.readfilesync (). The last parameter of the Async method function is a callback function, and the first parameter of the callback function contains the error message (ERR).

We recommend that you use asynchronous methods, which are more efficient, faster, and not blocking than synchronous.

1. Open file,fs. Open(path, flags[, mode], callback)

2, through the asynchronous mode to obtain the file information,FS. Stat(path, callback)

When Fs.stat (path) executes, an instance of the stats class is returned to its callback function. You can determine the related properties of a file by providing a method in the stats class. For example, determine whether the file is:

var fs = require ('fs'); Fs.stat ('/users/liuht /code/itbilu/demo/fs.js', function (err, stats) {    console.log (Stats.isfile ());          // true})

Learn about the methods in the stats class.

3. Write the file in asynchronous mode,FS. WriteFile(file, data[, options], callback)

WriteFile directly open the file by default is W mode, so if the file exists, the content written by this method overwrites the old file content.

< Span class= "pun" > 4, read files in asynchronous mode, fs.read (fd, buffer , Offset, Length, Position, Callback)

< Span class= "pun" >< Span class= "pun" >< Span class= "pun" >< Span class= "pun" > FD-the file descriptor returned by the Fs.open () method.

< Span class= "pun" >5, asynchronous mode close file, fs.close (fd, callback /span>

< Span class= "pun" >6, asynchronous mode intercept file, fs.ftruncate (fd, len , Callback)

< Span class= "pun" >7, delete files, fs. Unlink (path, Callback )

8, create directory, fs. (path[, Mode],< Span class= "PLN" > Callback)

9, read the directory, FS. Readdir(path, callback)

10. Delete directory,FS. RmDir(path, callback)

There are many other ways to check the API

NODE.JS:WEB module, File system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.