In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to use Express and AbsurdJS to do Node.js applications, in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
There are many new technologies attracting more and more developers nowadays, and Node.js is one of them. Mainly because it is JavaScript-driven, many people are interested. In this tutorial, I will teach you how to use AbsurdJS with Express. Express is a popular Node.js framework, while AbsurdJS is relatively new. I hope you will find it useful after reading it.
Brief introduction
As I mentioned, Express is very popular. Because it is one of the earliest Node.js frameworks. It does all the trivial things, such as routing, parameter parsing, templates, and sending responses to browsers. Its library encapsulates the native Node.js based on the middleware architecture provided by Connect.
AbsurdJS started out as a CSS preprocessor. The goal is to bring more flexibility to CSS developers. It accepts pure JavaScript code and converts it to CSS. Everyone's feedback on it is relatively positive, and I am trying to continue to improve it. Now it can not only preprocess CSS, but also handle HTML. It accepts JSON and YAML and successfully exports it for client use.
Steps
In order for the project made by * * to run, we need to install Node.js. Just open nodejs.org and click the big green "INSTALL" button. After the download and installation is complete, you can call the Node.js script to install the dependent package using npm (Node's package manager).
Create a new folder for your project and create an empty "package.json" file in it. The package manager will use this file as a starting point to install the packages we need. We only need two packages, so the json file should look like this:
{"name": "AbsurdJSAndExpress", "description": "AbsurdJS + Express app", "version": "0.0.1", "dependencies": {"express": "3.4.4", "absurd": "*"}}
Of course, there are many other parameters that can be configured, but for convenience, let's follow the above configuration first. Open the terminal, locate the directory contained in Package.json, and execute:
Npm install
The node_modules folder is generated in the current directory, and Express and AbsurdJS are downloaded automatically.
Run the server
With Express, you can run a http server with just a few lines of code.
Var express = require ('express'), app = express (); app.listen (3303); console.log (' Listening on port 3303')
Save the above code as app.js and run:
Node app.js
The console should display "Listening on port 3303". When the browser opens http://localhost:3303/, it will see:
Cannot GET /
Don't worry, this is normal because we haven't added routes yet.
Add rout
Express provides a friendly API to define URL routing. Let's simply add one here and paste the following code into app.js.
App.get ('/', function (req, res, next) {res.setHeader ('Content-Type',' text/html'); res.send ("application");})
A few things have been done here. The * * parameters of the .get method define the path; the second parameter is a method that handles the request, which accepts three parameters-request, response, and next. The advantage here is that we can pass in multiple functions, which will be called one by one. All we need to do is execute next (), otherwise the next method will not be called. For example:
App.get ('/', function (req, res, next) {console.log ("do some other stuff here"); next ();}, function (req, res, next) {res.send ("application");})
A common practice in routing definitions is to add some reusable tasks as middleware. For example, we have two kinds of Content-Type, HTML and CSS. It is more flexible to use the following methods.
Var setContentType = function (type) {return function (req, res, next) {res.setHeader ('Content-Type',' text/' + type); next ();}} app.get ('/', setContentType ("html"), function (req, res, next) {res.send ("application");})
If we need to provide CSS, just use setContentType ("css").
Provide HTML
Many Express tutorials and articles introduce some template engines. It's usually Jade, Hogan, or Mustache. However, if we use AbsurdJS, we don't need a template engine. We can write HTML in pure JavaScript. More specifically, use the JavaScript object. Let's start with the landing page. Create a new folder pages and create a new landing.js file in it. We are using Node.js, so the file should contain:
Module.exports = function (api) {/ /...}
Note that the returned function accepts a reference to AbsurdJS API. This is exactly what we want. Now add a little more HTML:
Module.exports = function (api) {api.add ({_: ", html: {'meta [http-equiv=" Content-Type "content=" text/html; charset=utf-8 "]': {}, 'link [rel=" stylesheet "type=" text/css "href=" styles.css "]: {}}, body: {}});}
Strings added by the "_" attribute are not converted when compiled into HTML; the other attributes define a tag each. There are other ways to define tag attributes, but I think it's better to use the above approach. The idea came from Sublime's Emmet plug-in. When compilation is complete, the following is generated:
This tutorial has only one page, but in reality you may use the same HTML in multiple pages. At this point, it makes more sense to move this part of the code to an external file and reference it when needed. Of course, repeatable templates can also be used here. Create the file / pages/partials/layout.js:
Module.exports = function (title) {return {_: ", html: {head: {'meta [http-equiv=" Content-Type "content=" text/html; charset=utf-8 "]: {},' link [rel=" stylesheet "type=" text/css "href=" styles.css "]: {}, title: title}, body: {}};}
This is actually a function that returns the object. So, the previous landing.js can be changed to:
Module.exports = function (api) {var layout = require (". / partials/layout.js") ("Home page"); api.add (layout);}
As you can see, the layout template accepts title variables. In this way, part of the content can be generated dynamically.
Next is to add content to the body tag. It's very simple because everything is a pure JavaScript object.
Module.exports = function (api) {var layout = require (". / partials/layout.js") ("Home page"); layout.html.body = {H2: "Page content"} api.add (layout);}
The resulting result:
Home page Page content
The code in this article looks short and incomplete because it would be too long to write it all. Next, I will only introduce the idea of creating unordered lists, because this is more interesting. The rest is similar to layout, so it is no longer mentioned.
Here is a snippet that generates an unordered list. Label:
Module.exports = function (data) {var html = {ul: []}; for (var iTuno; item=data [I]; iTunes +) {html.ul.push ({li: item});} return html;}
Only one ul attribute is used to define an object. A ul is actually an array full of items in a list.
Var list = require (". / partials/list.js"); var link = require (". / partials/link.js"); list ([link ("http://krasimir.github.io/absurd"," Official library site "), link (" https://github.com/krasimir/absurd", "Official repository")])
Link is also a fragment, similar to this:
Module.exports = function (href, label) {return {a: {_ attrs: {href: href}, _: label}
When combined, it produces:
Official library site Official repository
Now, imagine we have a bunch of clips that we can use. If they are written flexibly enough, they only need to be created once to be passed between projects. AbsurdJS is so powerful that as long as we have a set of predefined collections that are good enough, we can write HTNL tags quickly and more descriptively.
* * when the HTML has been completed, we just need to compile and send it to the user. So, make a small change to app.js so that our application responds to the correct tag:
Var absurd = require ("absurd"); var homePage = function (req, res, next) {absurd (). Morph ("html"). Import (_ _ dirname + "/ pages/landing.js"). Compile (function (err, html) {res.send (html);});} app.get ('/', setContentType ("html"), homePage)
Provide CSS
With the HTML type, first add a route to the style.css in app.js.
Var styles = function (req, res, next) {absurd (). Import (_ _ dirname + "/ styles/styles.js") .compile (function (err, css) {res.send (css);});} app.get ('/ styles.css', setContentType ("css"), styles)
Use JavaScript to define CSS. Anything can be placed in a separate Node.js module. Let's create / styles/styles.js and add the code:
Module.exports = function (api) {api.add ({body: {width: 100%, height: 100%, margin: 0, padding: 0, fontSize: "16px", fontFamily: "Arial", lineHeight: "30px"})}
A simple style control. Notice that properties with dashes are rewritten to hump case style. Otherwise, you will be warned if you cannot create a valid object.
Now suppose you want to control the style of and labels. They are all headings, the same color and font, but not the same size. AbsurdJS intelligently outputs the correct style in the following ways.
Var title = function () {return {color: "# 2C6125", fontWeight: "normal", fontSize: "40px", fontFamily: "Georgia", padding: "20px 10px"}} api.add ({H2: title (), h3: [title (), {fontSize: "30px"}]})
Output result:
H1, H2 {color: # 2C6125; font-weight: normal; font-family: Georgia; padding: 20px 10px;} H1 {font-size: 40px;} H2 {font-size: 30px;}
The preprocessor collects the same style that is defined only once and creates new definitions for different styles.
If you plan to use Node.js,Express, it will be one of the starting points for *. It's not super powerful, but it's still easy to use. It has the basic elements needed to develop web applications. Then to extend it, using AbsurdJS will bring a lot of fun to the development, because the whole application is written in pure JavaScript.
This is the answer to the question about how to use Express and AbsurdJS to do Node.js application. I hope the above content can be of some help to everyone. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.