Deno 是一种用于 JavaScript 和 TypeScript 的安全运行时环境,它可以作为一个替代 Node.js 的工具,在构建 Web 应用和命令行工具时发挥重要作用。在本文中,我们将探讨如何使用 Deno 搭建一个简单的博客系统。
安装 Deno
Deno 的安装非常简单。以下是在 macOS 上安装 Deno 的步骤:
brew install deno
Windows 用户可以在 PowerShell 中运行以下命令:
iwr https://deno.land/x/install/install.ps1 -useb | iex
第一步:创建一个 HTTP 服务器
我们将使用 Deno 标准库中的 http 模块创建一个 HTTP 服务器。以下是示例代码:
// www.javascriptcn.com code example
import { serve } from "https://deno.land/std/http/mod.ts";
const server = serve({ port: 8000 });
console.log("Server started on http://localhost:8000/");
for await (const req of server) {
req.respond({ body: "Hello Deno!" });
}在终端运行命令:deno run --allow-net server.ts,然后在浏览器中打开 http://localhost:8000/,你将看到 Hello Deno!。
第二步:创建一个静态文件服务器
我们将使用 Deno 标准库中的 http 模块和 serveStatic 函数创建一个静态文件服务器。以下是示例代码:
// www.javascriptcn.com code example
import { serveStatic } from "https://deno.land/std/http/file_server.ts";
import { serve } from "https://deno.land/std/http/mod.ts";
const PORT = 8000;
const server = serve({ port: PORT });
console.log(`Static file server started on http://localhost:${PORT}`);
for await (const req of server) {
const result = await serveStatic(req, ".", {
index: "index.html",
});
if (result) {
req.respond(result);
}
}在项目的根目录中创建一个index.html文件,然后在终端运行命令:deno run --allow-net --allow-read server.ts,然后在浏览器中打开 http://localhost:8000/,你将看到 index.html 文件的内容。
第三步:连接数据库
我们将使用 Deno 的第三方模块 deno_mysql 连接到 MySQL 数据库。使用以下命令安装:
deno install --allow-net --allow-env --allow-read https://deno.land/x/mysql/mod.ts
以下是示例代码:
// www.javascriptcn.com code example
import { Client } from "https://deno.land/x/mysql/mod.ts";
const client = await new Client().connect({
hostname: "127.0.0.1",
username: "root",
password: "PASSWORD",
db: "blog",
});
console.log("Connected to MySQL!");请注意将“PASSWORD”替换为您的 MySQL 密码,将“blog”替换为您的数据库名称。
第四步:创建路由
我们将使用 Deno 的第三方模块 oak 创建路由。使用以下命令安装:
deno install --allow-net --allow-read --allow-plugin https://deno.land/x/oak/mod.ts
以下是示例代码:
// www.javascriptcn.com code example
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
const router = new Router();
router
.get("/", (ctx) => {
ctx.response.body = "Hello, Deno!";
})
.get("/posts", async (ctx) => {
const result = await client.query("SELECT * FROM posts");
ctx.response.body = result;
});
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
console.log("Server started.");
await app.listen({ port: 8000 });在终端中运行命令:deno run --allow-net --allow-env --allow-read server.ts,然后在浏览器中打开 http://localhost:8000/posts,你将看到从数据库中检索到的所有帖子。
我们已经成功地使用 Deno 搭建了一个简单的博客系统,这为我们构建更复杂的 Web 应用程序打下了坚实的基础。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d7ad0aa941bf7134dbf710