Home>Article>Web Front-end> Let’s talk about how to create a simple HTTP server using Node.js
How to create an HTTP server using NodeJS? The following article will introduce to you how to useNodeto create a simple HTTP server. I hope it will be helpful to you!
node.js
Thev8
engine based onChrome
runsjs
code, so we can get rid of the browser environment and runjs
code directly in the console , for example, the followinghello world
code
console.log('hello world');
can be run directly usingnode
in the console
node.js
’s built-in modulehttp
provides basichttp
Service capabilities, based on theCommonJS
specification, we can userequire
to import thehttp
module for usehttp
There is a ## in the module The #createServerfunction allows us to create a
httpserver It receives a callback function as a parameter. This callback function receives two parameters-
requestand
response
includes all Information requested by the client, such as
url, request header
header, request method and request body, etc.
is mainly used to return information to The client encapsulates some operations related to the response body. For example, the
response.writeHeadmethod allows us to customize the header information and status code of the return body
response.end()method to send the response body to the client. Using the
createServerfunction only creates a
Serverobject for us, but does not enable it to listen. We also need to call the
listen## of theserver
object. #The method can be used to listen, and it can actually start running as a server.
ip
, the third parameter is a callback function, which will be called asynchronously by thehttp
module. When an error is encountered, it can be called in the first parameter of this callback function. After getting the thrown exception, we can choose to handle the exception to make our server more robust
module to create a simple server
You can directly try to run it withconst { createServer } = require('http'); const HOST = 'localhost'; const PORT = '8080'; const server = createServer((req, resp) => { // the first param is status code it returns // and the second param is response header info resp.writeHead(200, { 'Content-Type': 'text/plain' }); console.log('server is working...'); // call end method to tell server that the request has been fulfilled resp.end('hello nodejs http server'); }); server.listen(PORT, HOST, (error) => { if (error) { console.log('Something wrong: ', error); return; } console.log(`server is listening on http://${HOST}:${PORT} ...`); });
and create a server that belongs to you! After the server is running, the browser can access the server by accessinghttp://localhost:8080
You can also use
nodemonRun it so that when our code changes, we don’t need to manually terminate the program and re-run it
It is recommended to install it globally so that it can be used directly without going throughnpm i -g nodemon
To use It is also very simple to use, just change thenode
command to thenodemon
commandnodemon http-server.js
andresp
objects earlier, we could not see any syntax prompts, and we must follow ## at any time. #nodeIt’s a bit inconvenient to check the official documentation while using it. But it doesn’t matter, we can use the
.d.tsfile of
tsto help us provide syntax prompts. Note that we are not using
tsfor development, just using it The syntax prompt function is only
Initialize the project--
Install
@types/node
Create the
jsconfig.json, there is no need to check it
{ "compilerOptions": { "checkJs": true }, "exclude": ["node_modules", "**/node_modules/*"] }
I wonder if you have found that there is actually an error in the above code?At this time, hover the mouse over thelisten
method, You can see the signature of the method可以看到,原来port
参数需要是number
类型,但是我们定义的时候是string
类型,所以没匹配上,将其修改为number
的8080
即可 而且可以直接查看到相关api
的文档,不需要打开node
官方的文档找半天去查看了
前面我们的简单http server
中只返回了一句话,那么是否能够返回多句话呢? 这就要用到resp
对象的write
方法了,end
只能够返回一次内容,而是用write
方法,我们可以多次写入内容到响应体中,最后只用调用一次end
,并且不传递任何参数,只让他完成发送响应体的功能
const { createServer } = require("http"); const HOST = "localhost"; const PORT = 8080; const server = createServer((req, resp) => { resp.writeHead(200, { "Content-Type": "text/plain" }); console.log("server is working..."); // write some lorem sentences resp.write("Lorem ipsum dolor sit amet consectetur adipisicing elit.\n"); resp.write("Omnis eligendi aperiam delectus?\n"); resp.write("Aut, quam quo!\n"); resp.end(); }); server.listen(PORT, HOST, (error) => { if (error) { console.log("Something wrong: ", error); return; } console.log(`server is listening on http://${HOST}:${PORT} ...`); });
这次我们写入了三句话,现在的效果就变成这样啦
我们不仅可以返回字符串给浏览器,还可以直接读取html
文件的内容并将其作为结果返回给浏览器 这就需要用到另一个Node.js
的内置模块 --fs
,该模块提供了文件操作的功能 使用fs.readFile
可以异步进行读取文件的操作,但是它不会返回promise
对象,因此我们需要传入回调去处理读取到文件后的操作 还可以使用fs.readFileSync
进行同步阻塞读取文件,这里我们选择异步读取
const { createServer } = require("http"); const fs = require("fs"); const HOST = "localhost"; const PORT = 8080;const server = createServer((req, resp) => { // change the MIME type from text/plain to text/html resp.writeHead(200, { "Content-Type": "text/html" }); // read the html file content fs.readFile("index.html", (err, data) => { if (err) { console.error( "an error occurred while reading the html file content: ", err ); throw err; } console.log("operation success!"); resp.write(data); resp.end(); }); }); server.listen(PORT, HOST, (error) => { if (error) { console.log("Something wrong: ", error); return; } console.log(`server is listening on http://${HOST}:${PORT} ...`); });
现在的结果就像下面这样:
成功将html
返回注意:这里需要将响应头的**Content-Type**
改为**text/html**
,告知浏览器我们返回的是**html**
文件的内容,如果仍然以**text/plain**
返回的话,浏览器不会对返回的内容进行解析,即便它是符合**html**
语法的也不会解析,就像下面这样:
当我们需要编写一个后端服务器,只负责返回接口数据的时候,就需要返回json
格式的内容了,相信聪明的你也知道该怎么处理了:
MIME
类型设置为application/json
resp.write
的时候传入的是json
字符串,可以使用JSON.stringify
处理对象后返回const { createServer } = require("http"); const HOST = "localhost"; const PORT = 8080; const server = createServer((req, resp) => { // change the MIME type to application/json resp.writeHead(200, { "Content-Type": "application/json" }); // create a json data by using an object const jsonDataObj = { code: 0, message: "success", data: { name: "plasticine", age: 20, hobby: "coding", }, }; resp.write(JSON.stringify(jsonDataObj)); resp.end(); }); server.listen(PORT, HOST, (error) => { if (error) { console.log("Something wrong: ", error); return; } console.log(`server is listening on http://${HOST}:${PORT} ...`); });
结果如下:
和之前返回html
文件的思路类似,都是一个设置响应头MIME
类型,读取文件,返回文件内容的过程 但是这次我们搞点不一样的 我们的思路是在服务器运行的时候生成一个pdf
文件,并将它返回 还需要将MIME
的类型改为application/pdf
生成pdf
文件需要用到一个库 --pdfkit
pnpm i pdfkit
首先我们编写一个创建pdf
文件的函数,因为创建pdf
文件还需要进行一些写入操作,不确定什么时候会完成,但是我们的请求必须等到pdf
文件创建完成后才能得到响应 所以我们需要将它变成异步进行的,返回一个promise
/** * @description 创建 pdf 文件 */const createPdf = () => { return new Promise((resolve, reject) => { if (!fs.existsSync("example.pdf")) { // create a PDFDocument object const doc = new PDFDocument(); // create write stream by piping the pdf content. doc.pipe(fs.createWriteStream("example.pdf")); // add some contents to pdf document doc.fontSize(16).text("Hello PDF", 100, 100); // complete the operation of generating PDF file. doc.end(); } resolve("success"); }); };
这里使用到了管道操作,将PDFDocument
对象的内容通过管道传到新创建的写入流中,当完成操作后我们就通过resovle
告知外界已经创建好pdf
文件了 然后在服务端代码中调用
const server = createServer(async (req, resp) => { // change the MIME type to application/pdf resp.writeHead(200, { "Content-Type": "application/pdf" }); // create pdf file await createPdf(); // read created pdf file fs.readFile("example.pdf", (err, data) => { if (err) { console.error( "an error occurred while reading the pdf file content: ", err ); throw err; } console.log("operation success!"); resp.end(data); }); }); server.listen(PORT, HOST, (error) => { if (error) { console.log("Something wrong: ", error); return; } console.log(`server is listening on http://${HOST}:${PORT} ...`); });
现在浏览器就可以读取到创建的pdf
文件了
思路依然是一样的,读取一个音频文件,然后通过管道将它送到resp
对象中再返回即可
const { createServer } = require("http"); const { stat, createReadStream } = require("fs"); const HOST = "localhost"; const PORT = 8080; const server = createServer((req, resp) => { // change the MIME type to audio/mpe resp.writeHead(200, { "Content-Type": "audio/mp3" }); const mp3FileName = "audio.mp3"; stat(mp3FileName, (err, stats) => { if (stats.isFile()) { const rs = createReadStream(mp3FileName); // pipe the read stream to resp rs.pipe(resp); } else { resp.end("mp3 file not exists"); } }); }); server.listen(PORT, HOST, (error) => { if (error) { console.log("Something wrong: ", error); return; } console.log(`server is listening on http://${HOST}:${PORT} ...`); });
效果如下
打开后就是一个播放音频的界面,这是chrome
提供的对音频文件的展示,并且打开控制台会发现有返回音频文件
注意:将音频文件流通过管道传到**resp**
后,不需要调用**resp.end()**
方法,因为这会关闭整个响应,导致音频文件无法获取
视频文件和音频文件的处理是一样的,只是MIME
的类型要改成video/mp4
,其他都一样
const { createServer } = require("http"); const { stat, createReadStream } = require("fs"); const HOST = "localhost"; const PORT = 8080; const server = createServer((req, resp) => { // change the MIME type to audio/mpe resp.writeHead(200, { "Content-Type": "audio/mp4" }); const mp4FileName = "video.mp4"; stat(mp4FileName, (err, stats) => { if (stats.isFile()) { const rs = createReadStream(mp4FileName); // pipe the read stream to resp rs.pipe(resp); } else { resp.end("mp4 file not exists"); } }); }); server.listen(PORT, HOST, (error) => { if (error) { console.log("Something wrong: ", error); return; } console.log(`server is listening on http://${HOST}:${PORT} ...`); });
我们学会了:
Node
创建一个http
服务器js
加上类型提示html
JSON
pdf
文件虽然内容简单,但还是希望你能跟着动手敲一敲,不要以为简单就看看就算了,看了不代表会了,真正动手实现过后才会找到自己的问题
更多node相关知识,请访问:nodejs 教程!
The above is the detailed content of Let’s talk about how to create a simple HTTP server using Node.js. For more information, please follow other related articles on the PHP Chinese website!