Hello World
var http = require (' http '); Request Agreement Http.createserver (function (request, response) {Response.writehead ($, {' Content-type ': ' text/html; charset= Utf-8 '}); Request header information, defined text type and character set if (request.url!== "/favicon.ico") { //clears 2nd this access Console.log (' Access '); Response.Write (' Hello, World '); Response.End (' Hell, World ');//Do not write the end of the HTTP protocol, but write a two-time Access }}). Listen (8000); Console.log (' Server running at Http://127.0.0.1:8000/');
/*
Start the service
CMD under execution:
Node N1_hello.js
Browser access: http://localhost:8000
*/
-----------------------------------------------------------------------------------------------------
node. js Call function
1. Local functions
var http = require (' http '); Http.createserver (function (request, response) { response.writehead ($, {' Content-type '): ' text/html; Charset=utf-8 '}); if (request.url!== "/favicon.ico") { fun1 (response);//Call local function Response.End ('); }}). Listen (8000); Console.log (' Server running at http://127.0.0.1:8000/'); function Fun1 (res) {Console.log ("fun1"); Res.write ("Hello, I am fun1");}
2. Functions that call other JS files
Na_node.js
var http = require (' http '); var otherfun = require ("./model/otherfun.js");//Insert other JS file Http.createserver (function (request, response) { Response.writehead, {' Content-type ': ' text/html; Charset=utf-8 '}); if (request.url!== "/favicon.ico") { //otherfun (response); OTHERFUN.FUN2 (response);//You can directly point to the value//otherfun[' FUN3 '} (response);//You can also take a string value //------- Call the corresponding function with a string--- funname = ' fun3 '; Otherfun[funname] (response); Response.End (");}). Listen (8000); Console.log (' Server running at http://127.0.0.1:8000/');
Otherfun.js
Module.exports = {//supports multiple functions fun2:function (res) {Console.log ("I am fun2"); Res.write ("Hello, I am fun2");},fun3:function (res) { Console.log ("I am Fun3"); Res.write ("Hello, I am Fun3");} } /*function fun2 (res) {Console.log ("fun2"); Res.write ("Hello, I am fun2");} Module.exports = fun2; Only one function is supported */
node. js Hello World and Function call