Nodejs Basic Applications

Source: Internet
Author: User
This article mainly introduces the basic application of nodejs. It has good reference value. Let's take a look at the first nodejs Application below.

N1_hello.js

Console. log ('Hello word! ');

Execute the file in command line cmd (Open command line in the file ):

Node nw.hello.js

The command line cmd returns the result:

Hello word!

Ii. Basic nodejs format

// Step 1: Introduce the require module and load the require command into the http module var http = require ('http'); // Step 2: Create the Server http. createServer (function (request, response) {// send HTTP header // HTTP status value: 200: OK // content type: text/html response. writeHead (200, {'content-type': 'text/html; chaset = UTF-8; '}); // Step 3: accept the request and Response request if (request. url! = '/Favicon. ico '){...... // send response data response. end (''); // required. If not, there is no protocol end }}). listen (8000); // The terminal prints the following information: console. log ('server running at http: // 127.0.0.1: 8000 /');

3. Call functions in nodejs

----------------- Call a local function -----------------------------

Var http = require ('http'); http. createServer (function (request, response) {response. writeHead (200, {'content-type': 'text/html; chaset = UTF-8; '}); if (request. url! = '/Favicon. ico ') {fun1 (response); // send response data response. end ('');}}). listen (8000); // The terminal prints the following information: console. log ('server running at http: // 127.0.0.1: 8000/'); function fun1 (res) {console. log ('fun1'); res. write ('Hello, I am fun1 ');}

----------------- Call an external function -----------------------------

Note: external functions must be written in module. exports. exports is an interface exposed by the module.

------------ (1) only calls one function -----------

In the main program:

Var http = require ('http'); var otherfun = require (". /models/otherfuns. js "); // call the fun2http of the external page. createServer (function (request, response) {response. writeHead (200, {'content-type': 'text/html; chaset = UTF-8; '}); if (request. url! = '/Favicon. ico ') {otherfun (response); // response when a function is supported. end ('');}}). listen (8000); // The terminal prints the following information: console. log ('server running at http: // 127.0.0.1: 8000 /');

Otherfuns. js

Function fun2 (res) {console. log ('fun2'); res. write ('Hello !, I'm fun2');} module. exports = fun2; // only one function is supported.

------------ (2) call multiple functions -----------

In the main program:

Var http = require ('http'); var otherfun = require (". /models/otherfuns. js "); // call the otherfuns external page of The Write function. jshttp. createServer (function (request, response) {response. writeHead (200, {'content-type': 'text/html; chaset = UTF-8; '}); if (request. url! = '/Favicon. ico ') {// todo object. the method name calls otherfun. fun2 (response); otherfun. fun3 (response); // todo calls the corresponding function as a string (the result is the same as above) // otherfun ['fun2'] (response ); // otherfun ['fun3'] (response); response. end ('');}}). listen (8000); // The terminal prints the following information: console. log ('server running at http: // 127.0.0.1: 8000 /');}

Otherfuns. js

Module. exports = {fun2: function (res) {// anonymous function console. log ('fun2'); res. write ('Hello !, I'm fun2'); // output on the page}, fun3: function (res) {console. log ('fun3'); res. write ('Hello !, I'm fun3 ');},......}

Iv. nodejs route preliminary

Main Program n4_rout.js:

Var http = require ('http'); // introduce the url module var url = require ('url'); http. createServer (function (request, response) {response. writeHead (200, {'content-type': 'text/html; chaset = UTF-8; '}); if (request. url! = '/Favicon. ico ') {var pathname = url. parse (request. url ). pathname; pathname = pathname. replace (//, ''); // replace the previous/console. log (pathname); response. end ('');}}). listen (8000); // The terminal prints the following information: console. log ('server running at http: // 127.0.0.1: 8000 /');

Run the file in command line cmd and enter the route address in access: http: // localhost: 8000/, for example, and observe the command line.

V. nodejs reading files

Main Program:

Var http = require ('http'); var optfile = require ('. /models/optfile '); // import the file http. createServer (function (request, response) {// send HTTP header // HTTP status value: 200: OK // content type: text/html response. writeHead (200, {'content-type': 'text/html; chaset = UTF-8; '}); if (request. url! = '/Favicon. ico ') {// clear 2nd accesses to the optfile. readfileSync ('. /views/login.html '); // synchronously calls the readfileSync () method to read files. // optfile. readfile ('. /views/login.html ', response); // calls the readfile () method response asynchronously. end ('OK !!!!! '); // Do not write the console. log ('the main program has been executed! ') ;}}). Listen (8000); // The terminal prints the following information: console. log ('server running at http: // 127.0.0.1: 8000 /');

In optfile. js:

Var fs = require ('fs'); // Node: class module for importing file system module (fs) syntax to fs operation file. exports = {readfileSync: function (path) {// synchronously read var data = fs. readFileSync (path, 'utf-8'); // read the path of the synchronization file in Chinese. log ("the synchronization method has been executed. ") ;}, Readfile: function (path) {// asynchronously reads fs. readFile (path, function (err, data) {if (err) {console. error (err);} else {console. log ("Asynchronous read:" + data. toString () ;}}); console. log ("Asynchronous Method execution is complete. ");},}

Result: In command line cmd

(1) Synchronous file reading:

The above is all the content of this article. I hope this article will help you in your study or work, and I also hope to support PHP!

For more articles about nodejs basic applications, refer to PHP!

Related Article

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.