search

How to stop nodejs

Oct 20, 2021 pm 02:36 PM
nodejs

停止nodejs的方法:1、通过“Ctrl+C”来关闭NodeJS服务器;2、判断客户端提交的请求信息,并调用“server.close()”关闭服务器即可。

How to stop nodejs

本文操作环境:windows7系统、nodejs10.16.2版、Dell G3电脑。

怎么停止nodejs?

NodeJS服务器退出:完成任务,优雅退出 :

首先,不能共享完毕之后,都通过Ctrl+C来关闭NodeJS服务器。

其次,如果仅仅能向客户端提供d:\ilinkit_logo.png文件的下载,是没有意义的,共享哪个文件,应该可以通过传入的参数来指定。

老规矩,先上一个图:

我们首先来实现退出功能,如果客户端向服务器提交了http://localhost:8000/exit的请求,我们就执行服务器的退出操作。

上一篇文章我们已经能够识别出/xiaohong的请求,所以这个实现起来很简单,代码如下:

var http = require( 'http' );
var fs = require('fs');
var url = require( 'url' );

var file_path = "D:\\ilinkit_logo.png" ;
var file_stream ;
var buffer_box = [] ;
var file_length = 0 ;

var file_name = file_path.substr( file_path.lastIndexOf('\\')+1 );

fs.stat( file_path , function ( err , stat ){
            if (err) {
                if ('ENOENT' == err.code) {
                    console.log( 'File does not exist...' );
                } else {
                    console.log( 'Read file exception...' );
                }
            } else {
                file_stream = fs.createReadStream( file_path );
                file_stream.on( 'data' , function( chunk ){
                    buffer_box.push( chunk ) ;
                    file_length += chunk.length ;
                } );
                file_stream.on( 'end' , function(  ){
                    console.log( "文件读取完毕" );
                } );
                file_stream.on('error', function(err){
                    console.log( "文件读取失败!" );
                });

                var server =http.createServer( function ( request ,response ){
                  var h_name = request.headers.host ;
                  var h_path = url.parse( request.url ).pathname ;

                  if( h_path === '/xiaohong' ){
                    response.setHeader( 'Content-Type' , 'application/octet-stream' );
                    response.setHeader( 'Content-Disposition' , 'attachment; filename=' + encodeURIComponent(file_name) );

                    for( var buffer_index = 0 ; buffer_index<buffer_box.length ; buffer_index++ )
                    {
                        response.write( buffer_box[buffer_index] );
                    }
                    response.end();
                   }
                   else if( h_name === &#39;localhost:8000&#39; && h_path === &#39;/exit&#39; ){
                    response.end(&#39;Bye!&#39;);
                    server.close() ;
                    console.log( &#39;Bye!&#39; );
                   }
                   else{
                    response.end( &#39;Hello, iLinkIT&#39; );
                   }

                } );
                server.listen( 8000 );
                console.log( &#39;HTTP服务器启动中,端口:8000.....&#39; );

            }//end else,读取文件没有发生错误
});

关键的代码解析如下:

第33行,我们通过request对象获取客户端请求的主机及端口内容。

第46行~第50行,我们判断客户端提交的请求信息,如果是http://localhost:8000/exit,则调用server.close()关闭服务器。为什么要判断是不是localhost提交的请求?因为我们希望仅仅在服务器本地提交的请求才能关闭NodeJS服务器。

验证方式如下:

1. 启动服务器:打开命令行,进入js脚本所在的位置,执行:node h_ilinkit_1.js

2. 打开浏览器,输入:http://localhost:8000,显示如下:

说明当前服务器启动正常。

3. 打开浏览器,输入:http://localhost:8000/exit。

提示NodeJS服务器已经关闭,我们把浏览器关闭之后,发现服务器已经正常退出,如下所示。

这样,我们就没必要每次为了退出服务器,都去按Ctrl + C了。

 

通过请求退出服务器就介绍到这里,接下来我们再看一下,如果在启动NodeJS服务器的时候,给它传入参数。对应到我们爱莲(iLinkIT)的场景,希望能够将要共享的文件的路径作为参数传递给NodeJS服务器,服务器根据传入的文件路径读取数据到缓冲区,接受客户端的响应。

代码如下:

var http = require( &#39;http&#39; );
var fs = require(&#39;fs&#39;);
var url = require( &#39;url&#39; );

var args = process.argv.splice( 2 );
var file_path = args.join( &#39;&#39; ) ;
var file_stream ;
var buffer_box = [] ;
var file_length = 0 ;

var file_name = file_path.substr( file_path.lastIndexOf(&#39;\\&#39;)+1 );

fs.stat( file_path , function ( err , stat ){
            if (err) {
                if (&#39;ENOENT&#39; == err.code) {
                    console.log( &#39;File does not exist...&#39; );
                } else {
                    console.log( &#39;Read file exception...&#39; );
                }
            } else {
                file_stream = fs.createReadStream( file_path );
                file_stream.on( &#39;data&#39; , function( chunk ){
                    buffer_box.push( chunk ) ;
                    file_length += chunk.length ;
                } );
                file_stream.on( &#39;end&#39; , function(  ){
                    console.log( "文件读取完毕" );
                } );
                file_stream.on(&#39;error&#39;, function(err){
                    console.log( "文件读取失败!" );
                });

                var server =http.createServer( function ( request ,response ){
                  var h_name = request.headers.host ;
                  var h_path = url.parse( request.url ).pathname ;

                  if( h_path === &#39;/xiaohong&#39; ){
                    response.setHeader( &#39;Content-Type&#39; , &#39;application/octet-stream&#39; );
                    response.setHeader( &#39;Content-Disposition&#39; , &#39;attachment; filename=&#39; + encodeURIComponent(file_name) );

                    for( var buffer_index = 0 ; buffer_index<buffer_box.length ; buffer_index++ )
                    {
                        response.write( buffer_box[buffer_index] );
                    }
                    response.end();
                   }
                   else if( h_name === &#39;localhost:8000&#39; && h_path === &#39;/exit&#39; ){
                    response.end(&#39;Bye!&#39;);
                    server.close() ;
                    console.log( &#39;Bye!&#39; );
                   }
                   else{
                    response.end( &#39;Hello, iLinkIT&#39; );
                   }

                } );
                server.listen( 8000 );
                console.log( &#39;HTTP服务器启动中,端口:8000.....&#39; );

            }//end else,读取文件没有发生错误
});

关键代码解析如下:

第5行,通过process.argv.splice( 2 )获得了传入的命令行参数。

之前我们启动NodeJS服务器的命令为:node h_ilinkit_1.js,而要传入参数之后,执行的命令为node h_ilinkit_2.js d:\ilinkit_logo.rar

process.argv会将输入命令行的所有的内容都获取到,包括node h_ilinkit_2.js部分,我们通过调用splice( 2 ),获得传入的第3个参数的内容,将前面的两个字符串剔除掉。

第6行,将输入命令行的内容中,除了node h_ilinkit_2.js之外的内容合并在一起,作为文件路径。

 

验证方式如下:

1. 启动服务器:打开命令行,进入js脚本所在的位置,执行:node h_ilinkit_2.js d:\ilinkit_logo.rar,如下图所示:

3. 打开浏览器,输入:http://localhost:8000/xiaohong,显示如下:

可见,我们已经实现了通过命令行传入参数的功能,因为我们传入的是d:\ilinkit_logo.rar,所以,客户端提交请求后,下载到的文件也是ilinkit_logo.rar。

简单回顾一下:

1. 借助NodeJS的服务器响应机制,通过给服务器提交/exit的请求,实现服务器的退出操作。

2. 通过在启动NodeJS时,向服务器传入共享文件的路径,实现共享文件的自定义,这样,想共享哪个文件,就可以共享哪个文件。

推荐学习:《node.js视频教程

The above is the detailed content of How to stop nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment