1605367500
As a server-side developer, it is however necessary to understand the concept of routing and middleware. In this article we’ll emphasize more on E**xpress.JS (**a back-end web application framework for Node.js).
Routes refers to paths for which data travels on a network. It can also be said to be a way taken in getting from a starting point to a destination.
So let’s think of routes this way, if my starting point is “A” and my destination is “B” then the path to which I follow from my starting point “A” to get to destination “B” is my route.
Routes are created so as to determine the data that should be delivered given any URL.
For instance, when we type in www.google.com in a browser, the response we get is the data which has been determined by a developer(s) which is delivered to the URL www.google.com.
LINUS TOLVARDS will say… “TALK IS CHEAP. SHOW ME THE CODE” 😂
First of all let’s create a folder that houses our code. To do so
open up your terminal and get your fingers to work.😊
1. _cd Documents_ 👉(This will take you to document directory, if you're already there jump to step 2).
_mkdir my-first-route_ 👉(This will create a new directory called “my-first-route” inside your Document directory)
_cd my-first-route_ 👉(This will take you to “my-first-route” directory)
_touch app.js_ (This will create a new file called “app.js” in “my-first-route” directory)
_npm init_ 👉(This will let you setup your npm package)
_npm install express — save_ 👉(This will install “express” and save it as a dependency in this project)
Having typed in the command, we should have our files and folders in this structure
Folder Structure
so let’s keep it going …
Type in these codes in our app.js file
const app = require("express")();
const PORT = 2000;
app.get("/", (req,res) =>{
res.send("welcome to my homepage!!!!!!");
console.log("welcome page");
});
app.listen(PORT, ()=>{
console.log(`APP IS RUNNING ON PORT ${PORT}...`);
});
Writing Our Route
Now to start our server, type in
_node app.js _
in the terminal and hit enter
Our server is up and running
open up your browser and type in
CONGRATULATIONS… YOU’VE SUCESSFULLY CREATED A ROUTE🤗
#javascript #express #node #web-development #developer
1632537859
Not babashka. Node.js babashka!?
Ad-hoc CLJS scripting on Node.js.
Experimental. Please report issues here.
Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.
Additional goals and features are:
Nbb requires Node.js v12 or newer.
CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).
Install nbb
from NPM:
$ npm install nbb -g
Omit -g
for a local install.
Try out an expression:
$ nbb -e '(+ 1 2 3)'
6
And then install some other NPM libraries to use in the script. E.g.:
$ npm install csv-parse shelljs zx
Create a script which uses the NPM libraries:
(ns script
(:require ["csv-parse/lib/sync$default" :as csv-parse]
["fs" :as fs]
["path" :as path]
["shelljs$default" :as sh]
["term-size$default" :as term-size]
["zx$default" :as zx]
["zx$fs" :as zxfs]
[nbb.core :refer [*file*]]))
(prn (path/resolve "."))
(prn (term-size))
(println (count (str (fs/readFileSync *file*))))
(prn (sh/ls "."))
(prn (csv-parse "foo,bar"))
(prn (zxfs/existsSync *file*))
(zx/$ #js ["ls"])
Call the script:
$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs
Nbb has first class support for macros: you can define them right inside your .cljs
file, like you are used to from JVM Clojure. Consider the plet
macro to make working with promises more palatable:
(defmacro plet
[bindings & body]
(let [binding-pairs (reverse (partition 2 bindings))
body (cons 'do body)]
(reduce (fn [body [sym expr]]
(let [expr (list '.resolve 'js/Promise expr)]
(list '.then expr (list 'clojure.core/fn (vector sym)
body))))
body
binding-pairs)))
Using this macro we can look async code more like sync code. Consider this puppeteer example:
(-> (.launch puppeteer)
(.then (fn [browser]
(-> (.newPage browser)
(.then (fn [page]
(-> (.goto page "https://clojure.org")
(.then #(.screenshot page #js{:path "screenshot.png"}))
(.catch #(js/console.log %))
(.then #(.close browser)))))))))
Using plet
this becomes:
(plet [browser (.launch puppeteer)
page (.newPage browser)
_ (.goto page "https://clojure.org")
_ (-> (.screenshot page #js{:path "screenshot.png"})
(.catch #(js/console.log %)))]
(.close browser))
See the puppeteer example for the full code.
Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet
macro is similar to promesa.core/let
.
$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)' 0.17s user 0.02s system 109% cpu 0.168 total
The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx
this adds another 300ms or so, so for faster startup, either use a globally installed nbb
or use $(npm bin)/nbb script.cljs
to bypass npx
.
Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.
To load .cljs
files from local paths or dependencies, you can use the --classpath
argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs
relative to your current dir, then you can load it via (:require [foo.bar :as fb])
. Note that nbb
uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar
in the namespace name becomes foo_bar
in the directory name.
To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:
$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"
and then feed it to the --classpath
argument:
$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]
Currently nbb
only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar
files will be added later.
The name of the file that is currently being executed is available via nbb.core/*file*
or on the metadata of vars:
(ns foo
(:require [nbb.core :refer [*file*]]))
(prn *file*) ;; "/private/tmp/foo.cljs"
(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"
Nbb includes reagent.core
which will be lazily loaded when required. You can use this together with ink to create a TUI application:
$ npm install ink
ink-demo.cljs
:
(ns ink-demo
(:require ["ink" :refer [render Text]]
[reagent.core :as r]))
(defonce state (r/atom 0))
(doseq [n (range 1 11)]
(js/setTimeout #(swap! state inc) (* n 500)))
(defn hello []
[:> Text {:color "green"} "Hello, world! " @state])
(render (r/as-element [hello]))
Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core
namespace is included with the let
and do!
macros. An example:
(ns prom
(:require [promesa.core :as p]))
(defn sleep [ms]
(js/Promise.
(fn [resolve _]
(js/setTimeout resolve ms))))
(defn do-stuff
[]
(p/do!
(println "Doing stuff which takes a while")
(sleep 1000)
1))
(p/let [a (do-stuff)
b (inc a)
c (do-stuff)
d (+ b c)]
(prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3
Also see API docs.
Since nbb v0.0.75 applied-science/js-interop is available:
(ns example
(:require [applied-science.js-interop :as j]))
(def o (j/lit {:a 1 :b 2 :c {:d 1}}))
(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1
Most of this library is supported in nbb, except the following:
:syms
.-x
notation. In nbb, you must use keywords.See the example of what is currently supported.
See the examples directory for small examples.
Also check out these projects built with nbb:
See API documentation.
See this gist on how to convert an nbb script or project to shadow-cljs.
Prequisites:
To build:
bb release
Run bb tasks
for more project-related tasks.
Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb
License: EPL-1.0
#node #javascript
1626694620
#stubborndevelopers
In this video we will learn below points:
************ Node.JS Tutorial in English 2021 Playlist ************
https://www.youtube.com/watch?v=gs0X92Yx70s&list=PLllIEssCHLKdNEVWsBQ5zcCxLu8Xpsl0E&index=2
************ React.JS Tutorial in Hindi 2021 Playlist ************
https://www.youtube.com/watch?v=F2A1qXcskP8&list=PLllIEssCHLKdRqOrDJdPIeW7nrwPPfa46
#node.js #express.stati #css #js #express js
1625235360
In this video, we’ll be going over how to quickly deploy your Node.js app to Heroku for FREE and how we can keep this app alive/online despite Heroku’s free tier’s limitations.
Building the Mars Rover Pictures of the Day App: https://www.youtube.com/watch?v=s5sygFQ_vLE
Kaffeine: https://kaffeine.herokuapp.com/
Other alternatives to keep Heroku apps alive:
Sections:
0:00 - Intro
0:22 - Discussing how to keep Heroku’s free apps alive
1:20 - Linking your Heroku app to your GitHub repo
2:47 - Setting up the server and GET endpoint to ping
7:09 - Setting up the config to start the app
8:46 - Verifying the deployment
9:36 - Keeping the app alive/online
10:23 - Conclusion
Found this video helpful? Feel free to support this channel here: https://ko-fi.com/jacksonyuan
#express.js #express #node.js #node #heroku's
1626747060
In this video series, we are going to learn Express JS by building a project. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
Along the way we are going to learn what is Express and how it works. Along with Express, we are also going to learn about other dependencies that are required for the backend. Finally, we will create an application that uses CRUD(create, read, update and delete) functionality.
In this video, we are going to use BodyParser dependency in order to get the data from the form.
Get the entire code of this series here : https://github.com/Bishwahangdewan/Learn-Express-by-building-a-Project
#express js #express #nodejs #js
1600052640
Hello all. In this blog, I am explaining how to perform routing with Node JS. Routing is one of the most important parts of any Web framework since it defines how our application should handle all the HTTP requests by the client.
Table of Content
Create a new directory and initialize node with the command npm init
.
mkdir helloworld
cd helloworld/
npm init -y
After executing the command, a package.json
file generated in the project’s root directory. This holds all the metadata relevant to the project.
On this file, we see something called scripts. This is the place where we add our own commands for the project. I am creating a new command which starts my server when I type npm start
. The script tells node that it should run the command node index.js
every time when I execute the command npm start
.
package.json
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
2. Creating a simple Server with Express JS
Now let’s create our server. Here we are creating our server using Express.js
. Express JS is an open-source web framework for node JS. It is designing for building web apps and APIs. The below command installs express to our project.
npm install express --save
We are using express to create a new server that will be running on the port 8000. Also for the demonstration, I am creating a route that returns hello world.
index.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(8000, function () {
console.log('Listening to Port 8000');
});
Now start the server, you should see hello world being displayed in the browser.
npm start
#joan-louji #nodejs #routing #expressjs #express-routing #express