node.js教程基础:第一个node.js程序

第一个Node.js程序

可以是基于控制台console和基于Web的node.js应用程序。

基于consolenode.js例子

文件:console_example1.js

1 console.log('Hello World); 

打开Node.js命令提示符并运行以下代码:

>node console_example1.js

>Hello World

在这里,console.log()函数在控制台上显示消息。

我们还可以在console.log()函数中使用格式说明符:

1 console.log('Hello %s', World);   

Node.js控制台模块提供了一个简单的调试控制台,类似于Web浏览器提供的JavaScript控制台机制。

可以使用三种控制台方法来编写任何node.js流:

1)   console.log()用于在控制台显示简单消息

2)   console.Error()用于在控制台上显示错误消息,如

1 console.error(new Error('Hell! This is a wrong method.')); 

3) console.warn()用于在控制台上显示警告消息,如

1 const name = 'John'; 
2 console.warn(`Don't mess with me ${name}! Don't mess with me!`);  

基于webnode.js例子

node.js web应用程序包含以下三个部分:

1)导入所需的模块:”require”指令用于加载Node.js模块。

2)创建服务器:您必须建立一个服务器,该服务器将侦听客户端的请求,类似于Apache HTTP Server。

3)读取请求并返回响应:在第二步中创建的服务器将读取客户端发出的HTTP请求(可以是浏览器或控制台)并返回响应。

如何创建node.js web应用程序

步骤如下:

1)导入所需的模块:第一步是使用require指令以加载http模块并将返回的HTTP实例存储到http变量中。 例如:

1 var http = require("http"); 

2)创建服务器:在第二步中,您必须使用创建的http实例并调用http.createServer()方法来创建服务器实例,然后使用与服务器实例相关联的listen方法将其绑定在端口8081上。 向其传递带有请求和响应参数的函数,并编写示例实现以返回”Hello World”。 例如:

 1 http.createServer(function (request, response) {  
 2    // Send the HTTP header   
 3    // HTTP Status: 200 : OK  
 4    // Content Type: text/plain  
 5    response.writeHead(200, {'Content-Type': 'text/plain'});  
 6    // Send the response body as "Hello World"  
 7    response.end('Hello World
');  
 8 }).listen(8081);  
 9 // Console will print the message  
10 console.log('Server running at http://127.0.0.1:8081/');  

3)将step1和step2合并到一个名为“ main.js”的文件中。

文件:main.js

 1 var http = require("http"); 
 2 
 3 http.createServer(function (request, response) { 
 4    // Send the HTTP header  
 5    // HTTP Status: 200 : OK 
 6    // Content Type: text/plain 
 7    response.writeHead(200, {'Content-Type': 'text/plain'}); 
 8    // Send the response body as "Hello World" 
 9    response.end('Hello World
'); 
10 }).listen(8081); 
11 // Console will print the message 
12 console.log('Server running at http://127.0.0.1:8081/'); 

如何运行node.js服务

1)  转到开始菜单,然后单击Node.js命令提示符

2)  此时node.js命令窗口被打开

3)  切换到main.js路径

4)  执行node main.js

现在服务器已启动。

向Node.js服务器发出请求:

在任何浏览器中打开http://127.0.0.1:8081/。

您将看到以下结果:

            

现在,如果您对main.js文件进行了任何更改,则需要再次运行node main.js命令。

原文地址:https://www.cnblogs.com/MakeView660/p/12270954.html