From Node to Deno

栏目: IT技术 · 发布时间: 4年前

内容简介:Last week I published an article about Deno, and how to create aI've tried to collect some of the most used topics in Node, and looked for their alternative with Deno. First of all, I would like to make it clear that we can use many of the current Node.js

Original article: https://aralroca.com/blog/from-node-to-deno

Last week I published an article about Deno, and how to create a Chat app with Deno and Preact . Since then, many doubts have arisen. Mostly of them are about how to do the same thing we did in Node, but with the new Deno ecosystem.

I've tried to collect some of the most used topics in Node, and looked for their alternative with Deno. First of all, I would like to make it clear that we can use many of the current Node.js modules. There is no need to look for an alternative for everything, as many modules are reusable. You can visit pika.dev to look for modules to use in Deno. That said, let's start with the list:

We will cover the following:

Electron

With Node.js we can create desktop applications using Electron . Electron uses Chromium as interface to run a web environment. But, can we use Electron with Deno? Are there alternatives?

From Node to Deno

Well, right now Electron is far from being able to be executed under Deno. We must look for alternatives. Since Deno is made with Rust, we can use web-view rust bindings to run Destkop application in Deno.

This way, we can use the native OS webview to run as many webviews as we want.

Repo: https://github.com/eliassjogreen/deno_webview

import { WebView } from "https://deno.land/x/webview/mod.ts";

const contentType = 'text/html'
const sharedOptions = {
  width: 400,
  height: 200,
  resizable: true,
  debug: true,
  frameless: false,
};

const webview1 = new WebView({
  title: "Multiple deno_webview example",
  url: `data:${contentType},
    <html>
    <body>
      <h1>1</h1>
    </body>
    </html>
    `,
  ...sharedOptions,
});

const webview2 = new WebView({
  title: "Multiple deno_webview example",
  url: `data:${contentType},
    <html>
    <body>
      <h1>2</h1>
    </body>
    </html>
    `,
  ...sharedOptions,
});

await Promise.all([webview1.run(), webview2.run()]);

From Node to Deno

Forever / PM2

Forever and PM2 are CLI tools for ensuring that a given script runs continuously as a daemon. Unlike Forever, PM2 is more complete and also serves as load balancer. Both are very useful in Node, but can we use them in Deno?

Forever is intended for Node only, so using it is not feasible. On the other hand, with PM2 we can run non-node scripts, so we could still use it for Deno.

From Node to Deno

Creating an app.sh file

#!/bin/bash
deno run -A myCode.ts

And

➜ pm2 start ./app.sh

From Node to Deno

Express / Koa

Express and Koa are the best known Node frameworks. They're known for their robust routing system and their HTTP helpers (redirection, caching, etc). Can we use them in Deno? The answer is not... But there are some alternatives.

From Node to Deno

Http (std lib)

Deno's own STD library already covers many of the needs provided by Express or Koa. https://deno.land/std/http/ .

import { ServerRequest } from "https://deno.land/std/http/server.ts";
import { getCookies } from "https://deno.land/std/http/cookie.ts";

let request = new ServerRequest();
request.headers = new Headers();
request.headers.set("Cookie", "full=of; tasty=chocolate");

const cookies = getCookies(request);
console.log("cookies:", cookies);

However, the way to declare routes is not very attractive. So let's look at some more alternatives.

Oak (Third party lib)

One of the most elegant solutions right now, very inspired by Koa. https://github.com/oakserver/oak

import { Application,  } from "https://deno.land/x/oak/mod.ts";

const app = new Application();

app.use((ctx) => {
  ctx.response.body = "Hello World!";
});

await app.listen({ port: 8000 });

Abc (Third party lib)

Similar to Oak. https://deno.land/x/abc .

import { Application } from "https://deno.land/x/abc/mod.ts";

const app = new Application();

app.static("/static", "assets");

app.get("/hello", (c) => "Hello!")
  .start({ port: 8080 });

Deno-express (Third party lib)

Maybe the most similar alternative to Express Framework. https://github.com/NMathar/deno-express .

import * as exp from "https://raw.githubusercontent.com/NMathar/deno-express/master/mod.ts";

const port = 3000;
const app = new exp.App();

app.use(exp.static_("./public"));
app.use(exp.bodyParser.json());

app.get("/api/todos", async (req, res) => {
  await res.json([{ name: "Buy some milk" }]);
});

const server = await app.listen(port);
console.log(`app listening on port ${server.port}`);

MongoDB

MongoDB is a document database with a huge scability and flexibility. In the JavaScript ecosystem has been widely used, with many stacks like MEAN or MERN that use it. It's very popular.

From Node to Deno

So yes, we can use MongoDB with Deno. To do this, we can use this driver: https://github.com/manyuanrong/deno_mongo .

import { init, MongoClient } from "https://deno.land/x/mongo@v0.6.0/mod.ts";

// Initialize the plugin
await init();

const client = new MongoClient();
client.connectWithUri("mongodb://localhost:27017");

const db = client.database("test");
const users = db.collection("users");

// insert
const insertId = await users.insertOne({
  username: "user1",
  password: "pass1"
});

// findOne
const user1 = await users.findOne({ _id: insertId });

// find
const users = await users.find({ username: { $ne: null } });

// aggregation
const docs = await users.aggregation([
  { $match: { username: "many" } },
  { $group: { _id: "$username", total: { $sum: 1 } } }
]);

// updateOne
const { matchedCount, modifiedCount, upsertedId } = await users.updateOne(
  username: { $ne: null },
  { $set: { username: "USERNAME" } }
);

// deleteOne
const deleteCount = await users.deleteOne({ _id: insertId });

PostgresSQL

From Node to Deno

Like MongoDB, there is also a driver for PostgresSQL .

import { Client } from "https://deno.land/x/postgres/mod.ts";

const client = new Client({
  user: "user",
  database: "test",
  hostname: "localhost",
  port: 5432
});
await client.connect();
const result = await client.query("SELECT * FROM people;");
console.log(result.rows);
await client.end();

MySQL / MariaDB

From Node to Deno

As with MongoDB and PostgresSQL, there is also a driver for MySQL / MariaDB .

import { Client } from "https://deno.land/x/mysql/mod.ts";

const client = await new Client().connect({
  hostname: "127.0.0.1",
  username: "root",
  db: "dbname",
  poolSize: 3, // connection limit
  password: "password",
});

let result = await client.execute(`INSERT INTO users(name) values(?)`, [
  "aralroca",
]);
console.log(result);
// { affectedRows: 1, lastInsertId: 1 }

Redis

From Node to Deno

Redis , the best known database for caching, has also a driver for Deno.

import { connect } from "https://denopkg.com/keroxp/deno-redis/mod.ts";

const redis = await connect({
  hostname: "127.0.0.1",
  port: 6379
});
const ok = await redis.set("example", "this is an example");
const example = await redis.get("example");

Nodemon

From Node to Deno

Nodemon is used in development environment to monitor any changes in your files, automatically restarting the server. This makes node development much more enjoyable, without having to manually stop and restart the server to see the applied changes. Can it be used in Deno?

Sorry, but you can't... but still, there is an alternative: Denon.

We can use Denon as we use deno run to execute scripts.

➜ denon server.ts

Jest, Jasmine, Ava...

From Node to Deno

In the Node.js ecosystem there are a lot of alternatives for test runners. However, there isn't one official way to test the Node.js code.

In Deno, there is an official way, you can use the testing std library.

import { assertStrictEq } from 'https://deno.land/std/testing/asserts.ts'

Deno.test('My first test', async () => {
  assertStrictEq(true, false)
})

To run the tests:

➜  deno test

Webpack, Parcel, Rollup...

From Node to Deno

One of the strengths of Deno is that we can use ESmodules with TypeScript without the need for a bundler such as Webpack , Parcel or Rollup .

However, probably you wonder if given a tree of files, we can make a bundle to put everything in one file to run it on the web.

Well, it's possible, yes. We can do it with Deno's CLI. Thus, there's no need for a third-party bundler.

➜ deno bundle myLib.ts myLib.bundle.js

Now it's ready to be loaded in the browser:

<script type="module">
  import * as myLib from "myLib.bundle.js";
</script>

Prettier

From Node to Deno

In the last few years Prettier has become quite well known within the JavaScript ecosystem because with it you don't have to worry about formatting the files.

And the truth is, it can still be used on Deno but it loses its meaning, because Deno has its own formatter.

You can format your files using this command:

➜  deno fmt

NPM Scripts

From Node to Deno

With Deno, the package.json no longer exists. One of the things I really miss are the scripts that were declared in the package.json .

A simple solution would be to use a makefile and execute it with make . However, if you miss the npm syntax, there is an npm-style script runner for Deno:

You can define a file with your scripts:

# scripts.yaml
scripts:
  start: deno run --allow-net server.ts
  test: deno test --allow-net server_test.ts

Execute with:

➜  vr run <SCRIPT>

Another alternative is denox , very similar to Velociraptor.

Nvm

From Node to Deno

Nvm is a CLI to manage multiple active Node versions, to easy upgrade or downgrade versions depending on your projects.

A nvm equivalent in Deno is dvm .

➜  dvm use 1.0.0

Npx

Npx in recent years has become very popular to execute npm packages without having to install them. Now many projects won't exist within npm because Deno is a separate ecosystem. So, how can we execute Deno modules without having to install them with deno install https://url-of-module.ts ?

In the same way that we run our project, instead of a file we put the URL of the module:

➜  deno run https://deno.land/std/examples/welcome.ts

As you can see, not only we have to remember the name of the module, but the whole URL, which makes it a little more difficult to use. On the other hand it gives a lot more flexibility as we can run any file, not just what's specified as a binary in the package.json like npx .

Run on a Docker

From Node to Deno

To run Deno inside a Docker, we can create this Dockerfile:

FROM hayd/alpine-deno:1.0.0

EXPOSE 1993  # Port.

WORKDIR /app

USER deno

COPY deps.ts .
RUN deno cache deps.ts # Cache the deps

ADD . .
RUN deno cache main.ts # main entrypoint.

CMD ["--allow-net", "main.ts"]

To build + run it:

➜  docker build -t app . && docker run -it --init -p 1993:1993 app

Repo: https://github.com/hayd/deno-docker

Run as a lambda

From Node to Deno

To use Deno as a lambda, there is a module in Deno STD library. https://deno.land/x/lambda .

import {
  APIGatewayProxyEvent,
  APIGatewayProxyResult,
  Context
} from "https://deno.land/x/lambda/mod.ts";

export async function handler(
  event: APIGatewayProxyEvent,
  context: Context
): Promise<APIGatewayProxyResult> {
  return {
    body: `Welcome to deno ${Deno.version.deno}   `,
    headers: { "content-type": "text/html;charset=utf8" },
    statusCode: 200
  };
}

Interesting references:

Conclusion

I'm sure I forgot some Node topics and their Deno alternative, let me know if there's anything I missed that you'd like me to explain. I hope this article helps you break the ice with Deno.

To explore all libraries you can use with Deno:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Python基础教程(第2版)

Python基础教程(第2版)

Magnus Lie Hetland / 司维、曾军崴、谭颖华 / 人民邮电出版社 / 2010-7 / 69.00元

本书是经典教程的全新改版,作者根据Python 3.0版本的种种变化,全面改写了书中内容,做到既能“瞻前”也能“顾后”。本书层次鲜明、结构严谨、内容翔实,特别是在最后几章,作者将前面讲述的内容应用到了10个引人入胜的项目中,并以模板的形式介绍了项目的开发过程。本书既适合初学者夯实基础,又能帮助Python程序员提升技能,即使是 Python方面的技术专家,也能从书里找到令你耳目一新的东西。一起来看看 《Python基础教程(第2版)》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具