Overview
Have you heard about Deno? The new alternative to Node?
Deno is a secure runtime for Typescript and Javascript that uses v8 and built-in Rust. (Deno is an anagram of Node)
Deno doesn’t use the NPM/Yarn package manager, instead, it is a loading module by referring to file path or URLs.
Instructions for installation -> deno.land.
Highlights of Deno:
- Deno is secure by default unless you provide explicitly access to net or files
- Deno dies on uncaught errors.
- All async actions in Deno return a promise (You can use await anywhere ?).
- Scripts written in deno can be bundled into a single Js file.
There is no doubt about Node’s maturity, but deno is a thing to try
"node".split('').reverse().sort().join('')
Excited to drive in with deno? Let’s see a few real-life examples we usually deal with Nodejs and how we can achieve that in deno.
Creating HTTP server
While working with the servers we usually deal with middlewares and routers so oak ? is inspired by Koa and middleware routers inspired by @koa/router.
So hope you are ready with installation, create a file named server.ts
import { Application } from 'https://deno.land/x/oak/mod.ts' import router from './routes.ts' const port = 5000 const app = new Application() app.use(router.routes()) app.use(router.allowedMethods()) console.log(`Magic port ${port}`) await app.listen({ port })
The Application class wraps the serve() function. It has two methods: .use() and .listen().
Same as Node Middleware is added via the .use() method
Let’s achieve Hello world,
Add new file router.ts and controllers/index.ts
The Router class produces middleware which can be used with an Application to enable routing based on the pathname of the request.
// router.ts import { Router } from 'https://deno.land/x/oak/mod.ts' import { get } from './controllers/index.ts' const router = new Router() router.get('/', get) export default router
With a response we have properties like body, headers, status, type, and a method for redirection (redirect).
// controllers/index.ts const get = async (ctx: any) => { ctx.response.body = "Hello World!"; } export { get }
That’s it for hello world.
Need to run the server.ts file.
deno run –allow-net server.ts
Read about permission here –allow-net
Route to http://localhost:5000 and you will receive Hello world.
Serving simple HTML files and template parsing
Update the server.ts file with below code,
We can pass view engine as middleware, and update configuration like,
viewRoot will contain our static files folder name and viewExt will allow us to pass an extension of files like .html, .ejs or any other like Denjuck or Handlebars
import { Application } from 'https://deno.land/x/oak/mod.ts'; import { viewEngine, engineFactory, adapterFactory, ViewConfig } from 'https://deno.land/x/view_engine/mod.ts'; import router from './routes.ts' const port = 5000 const app = new Application() const ejsEngine = engineFactory.getEjsEngine(); const oakAdapter = adapterFactory.getOakAdapter(); app.use(viewEngine(oakAdapter, ejsEngine, { viewRoot: "./view", viewExt: ".html", })); app.use(router.routes()) app.use(router.allowedMethods()) console.log(`Magic port ${port}`) await app.listen({ port })
As well we have same root (“/”) route in controllers/index.ts file lets update that to serve HTML file,
const get = async (ctx: any) => { ctx.render("index"); } export { get }
Restarting the server and reloading the browser, didn’t work right?
Do you know what we missed?
We have used the read folder in our application and deno will not read until we provide a flag to read the files from our system.
So again run the server with deno run –allow-net –allow-read server.ts
Now it will work like charm ?.
We just served HTML files, what about EJS?
Let’s update the config in server.ts,
{ viewRoot: "./view", viewExt: ".ejs", }
Create a new file as index.ejs,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document&tt;/title> </head> <body> <h1>EJS HOLA</h1> Hobbies of <%=data.name%> </body> </html>
Now to render EJS file everything is same expect we have to dynamic data in EJS file so lets update controller/index.ts file
ctx.render("index", { data: { name: "Nikhil" } });
Now restart the server and you will see the output with EJS rendered.
Grab the code in case you missed something or not able to figure it out.
Too much time is wasted in restarting the server in development right? you can try denon.
Let’s keep exploring and wait for the upcoming recipe with me here for advanced concepts in deno.