Last Updated On By Khizer Ali
Deno has gained much popularity since its release on 13 May 2020. One of the reasons is that it is made by the creator of Node.js, Ryan Dahl. He pointed out some regrets about Node.js, which he wants to overcome by creating a new JavaScript runtime, which is now in the market in the form of Deno. The incredible features of deno sandbox and its security flags are declared in the slogan of the Deno. it says that:
In this article, we are going to discuss how the Deno is more secure than Node.js.
Table of Contents
By default, Deno executes the code inside a Sandbox, unlike Node.js, where you can easily access to the file system and environment. It means that in Deno, the runtime has no access to the network, the file system, the environment variable, and the execution of other scripts.
For example:
// app.ts
import { serve } from "https://deno.land/std/http/server.ts";
const server = serve({ port: 8000 });
console.log("http://localhost:8000/");
for await (const req of server) {
req.respond({ body: "Welcome to Deno\n" });
}
We will get the error if we try to run the above code in which we created a server.
This happened because we do not have the network access in Deno by default. If you want to give any permission, you have to do that explicitly with the help of security flags. These flags indicate the Deno that particular permissions are allowed.
So, in this example, we need –allow-net flag. Then it will work, and you will see the “Welcome to Deno” in your browser at localhost:8000/.
We have the following security flags available in Deno:
Allow write access.
Allow read system access.
Allow network access.
Allow environment access.
Allow loading plugins
Allow high resolution time measurement.
Allow subprocesses
Allow all permissions.
We have already seen the –allow-net. Now, let us check some other flags to see what happens when we try to read, write a file with or without permission flags.
Suppose we want to write a text in the file with the following code.
const encoder = new TextEncoder();
const intro = encoder.encode("Hello there,\n Welcome to the Deno site");
await Deno.writeFile("introduction.txt",intro);
On running this code directly, we will get the permission error.
Add the suitable flag that is –allow-write and then run.
Now, we need to read text from the same file which you just created
let file = await Deno.open("introduction.txt");
await Deno.copy(file, Deno.stdout);
file.close();
Running this file without a flag will result in a permission error.
We need to add an appropriate flag while running this file.
Security was one of the reasons why Ryan Dahl created an alternative of Node.js because Node.js does not have a built-in security model. However, deno sandbox and its security flags facilitate working in a secure environment. Because Deno script does not have access to your file system, your network, and your entire environment until you explicitly grant it.