What is Deno & can Node.js be replaced

We are going to understand basics of Deno here, And we also try to find out that can it replace Node.js or not? We will also write some code to understand Deno better. 

Deno has top 3 features which are better than Node.js and which makes it a secure and efficient runtime. These are:
  1. If you want to access network, file or environment variables then you need to provide explicit. 
  2. Deno supports Typescript which makes it type safe.
  3. It ships single executabale file (like in Java or .NET framework)

Lets install Deno on our system.
If you are on mac or linux then
    curl -fsSL https://deno.land/x/install/install.sh | sh
If you are on windows then
    iwr https://deno.land/x/install/install.ps1 -useb | iex

To print Hello World on Deno, is same like javascript. You need to use console.log to do that. The file extension can be .js (if you want to write in plain javascript) or .ts (if you want to write in Typescript).
console.log("Hello World");
You can access file by using below code:
for (let i = 0; i < Deno.args.length; i++) {
let filename = Deno.args[i];
let file = await Deno.open(filename);
await Deno.copy(file, Deno.stdout);
file.close();
}
You can use fetch to get/post request on an api:
const url = Deno.args[0];
const res = await fetch(url);
const body = new Uint8Array(await res.arrayBuffer());
await Deno.stdout.write(body);

We can create http server (we are familier with http.createServer() on Node.js):
const listener = Deno.listen({ port: 8080 });
console.log("listening on 0.0.0.0:8080");
for await (const conn of listener) {
Deno.copy(conn, conn);
}

Comments

Popular Posts