这篇文章主要介绍“如何使用node.js创建一个简单的Http服务器”,在日常操作中,相信很多人在如何使用node.js创建一个简单的HTTP服务器问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方
这篇文章主要介绍“如何使用node.js创建一个简单的Http服务器”,在日常操作中,相信很多人在如何使用node.js创建一个简单的HTTP服务器问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何使用Node.js创建一个简单的HTTP服务器”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
node.js
基于Chrome
的v8
引擎运行js
代码,因此我们可以摆脱浏览器环境,直接在控制台中运行js
代码,比如下面这个hello world
代码
console.log('hello world');
控制台中直接使用node
即可运行
node.js
的内置模块http
提供了基本的http
服务的能力,基于CommonJS
规范,我们可以使用require
导入http
模块进行使用http
模块中有一个createServer
函数能够让我们创建一个http
服务器
其接收一个回调函数作为参数,这个回调函数接收两个参数 -- request
和response
request
包括所有客户端请求的信息,比如url
、请求头header
、请求方式和请求体等
response
主要用于返回信息给客户端,封装了一些操作响应体相关的操作,比如response.writeHead
方法就可以让我们自定义返回体的头部信息和状态码
当我们将响应体处理好了之后,调用response.end()
方法就可以将响应体发送给客户端
使用createServer
函数只是帮我们创建了一个Server
对象,并没有让其开启监听,我们还需要调用server
对象的listen
方法才可以进行监听,真正作为一个服务器开始运行
listen
方法的第一个参数是监听的端口号,第二个参数则是绑定的主机ip
,第三个参数是一个回调函数,会被http
模块异步调用,当遇到错误的时候,就能够在这个回调函数的第一个参数中获取到抛出的异常 ,我们可以选择对异常进行处理,让我们的服务器更加健壮
下面是使用http
模块创建一个简单服务器的例子
const { 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} ...`);
});
可以直接尝试用node
运行它,创造一个属于你的服务器!服务器运行后,浏览器访问http://localhost:8080即可访问到这个服务器
也可以使用nodemon
运行它,这样当我们的代码发生变化的时候就不需要手动终止程序再重新运行了
npm i -g nodemon
建议全局安装它,这样就可以直接使用,不需要通过npx nodemon
去使用
使用也很简单,直接将node
命令改成nodemon
命令即可
nodemon http-server.js
前面我们在使用createServer
以及resp
对象的时候,看不到任何的语法提示,必须随时跟着node
官方文档去边用边查,有点不方便
但是没关系,我们可以使用ts
的.d.ts
文件帮助我们提供语法提示功能,注意,我们不是使用ts
进行开发,只是使用它的语法提示功能而已
初始化项目 -- npm init -y
安装@types/node
-- pnpm i @types/node -D
在项目目录下创建jsconfig.JSON
文件,将node_modules
排除在外,没必要对其进行检查
{ "compilerOptions": {
"checkJs": true
},
"exclude": ["node_modules", "**/node_modulesconst 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.js创建一个简单的HTTP服务器”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!
--结束END--
本文标题: 如何使用Node.js创建一个简单的HTTP服务器
本文链接: https://www.lsjlt.com/news/98851.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-30
2024-04-30
2024-04-30
2024-04-29
2024-04-29
2024-04-29
2024-04-18
2024-04-17
2024-04-11
2024-04-08
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0