停止nodejs的方法:1、通过“Ctrl+C”来关闭NodeJS服务器;2、判断客户端提交的请求信息,并调用“server.close()”关闭服务器即可。
本文操作环境: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 === 'localhost:8000' && h_path === '/exit' ){ response.end('Bye!'); server.close() ; console.log( 'Bye!' ); } else{ response.end( 'Hello, iLinkIT' ); } } ); server.listen( 8000 ); console.log( 'HTTP服务器启动中,端口:8000.....' ); }//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( 'http' ); var fs = require('fs'); var url = require( 'url' ); var args = process.argv.splice( 2 ); var file_path = args.join( '' ) ; 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 === 'localhost:8000' && h_path === '/exit' ){ response.end('Bye!'); server.close() ; console.log( 'Bye!' ); } else{ response.end( 'Hello, iLinkIT' ); } } ); server.listen( 8000 ); console.log( 'HTTP服务器启动中,端口:8000.....' ); }//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!

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.

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.

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.

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

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 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 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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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
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 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
Powerful PHP integrated development environment