Node. JS has been very popular recently, not only the open-source community is very concerned about it, but Microsoft has even provided official support for it to make node. JS can also run on Windows, Which is node. the further popularity of JS laid the foundation. This article will introduce the module management mechanisms of node. js and dojo, and introduce in detail the scheme of running the dojo framework on node. js. Finally, we use an example to demonstrate how to use the DTL module of dojo to parse a template file based on the Django template language.
A common view is that node. js makes JavaScript a server-side language, so naturally many people regard node. js as a web server. But not actually, node. javascript is just a javascript host environment. It interprets and runs JavaScript, and provides many native objects for JavaScript to do more, for example, network communication and file processing. Just like you can use Perl or Python to write a Web server, you can also use JavaScript to write a web server. Node. JS is suitable for creating Web Servers because it can efficiently process concurrent requests, but it is not a web server. To clarify this, we can use JavaScript like Perl to make it a tool language. When there is a product-level node. js-based Web server, it is easier for us to get started with Web server development.
Why do I need to run dojo on node?
Javascript itself is a very streamlined language with relatively simple functions, because it was originally intended not to develop complex applications, but to automate browser operations. In the face of increasingly complex front-end applications, many class libraries have emerged to solve this problem, such as jquery, extjs, dojo, and Yui. In addition to browser-compatible APIs, these libraries also provide a majority of functions that are purely used to enhance JavaScript functionality. This part of functions is common on the server side and on the browser side. I believe that if consistency is provided in this aspect, it must be enjoyed by the majority of Web developers, this is why I wrote this article.
Among the many class libraries, dojo is the most suitable for running node. js in all current class libraries, for four reasons:
- Both dojo and node. js are based on the module specification of commonjs.
- Dojo naturally supports node. JS, which effectively isolates browser-related code. The STARTUP script can automatically detect the node. js runtime environment without any modifications.
- The unit test framework and packaging tools used by dojo are both written in JavaScript and can be run directly on node. js. Therefore, Dojo + node. js can complete the entire application development lifecycle.
- Dojo has a complete object-oriented system and is suitable for the development of large-scale applications.
Dojo has always defined itself like this: javascript toolkit, rather than a simple framework that targets previous applications such as Ajax library. It can be seen that the enhancement of JavaScript is an important goal of dojo. It has a powerful object-oriented mechanism, event mechanism, and a wide range of tool libraries, it has provided a good foundation for the development of large-scale front-end applications. Now, it can play a role in node. js.
Module Loading Mechanism of node. js and dojo
Both node. js and dojo comply with the commonjs module specifications. Node. js supports the module1.0 specification, while dojo supports the AMD (asynchronous module definition, that is, asynchronous module definition) specification. Although there are two specifications, they both describe the module definition and loading mechanism, and have many in common. This provides a natural foundation for dojo to run on node. In the specification, JavaScript files and modules are in a one-to-one relationship. Each file is a module and can be referenced between modules through a relative path.
For node. JS, it is very easy to use a module. simply use the require function defined in module1.0 specifications. For example:
var fs = require('fs'); var content = fs.readFileSync('filePath' ,' utf8' );
FS is the file system operation module of node. js. You can use its identifier "FS" to load it and call the provided method. This method of module dependency is similar to that of traditional programming languages, such as Java import and C # Use.
However, amd specifications supported by dojo define an asynchronous loading mechanism, which is a little complicated. This specification emphasizes Asynchronization and requires a callback function to use the module. This callback function will be called after the dependent module is loaded. For example:
Define (['dojo/date'], function (date) {var zone = date. isleapyear (new date (); // obtain whether the current year is a leap });
The define function is defined by AMD specifications. Its first parameter is an array that contains the modules that this module depends on. After these modules are loaded, the second parameter is called: a callback function. The dependent modules are passed as parameters to the callback function in order for this module to use. The detailed usage of the define function is not described here. If you are interested, you can view the relevant normative documents. We only need to know that it is an asynchronous module definition and loading mechanism.
All modules in Dojo are defined by the define function. Obviously, node. JS, which does not support amd specifications, does not know the define function and cannot directly execute these modules. Therefore, Dojo must maintain its own module loading and execution, which fully complies with the behavior of dojo in the browser. It only reads the module code logic from the HTTP request to the Read File, other logics remain unchanged. The initialization code of dojo contains the detection of the node. js environment, and the module is automatically loaded using different methods according to the environment.
Based on commonjs specifications, node. js and dojo also introduce similar package concepts. A package is a folder in node. in JS, require ('packageidentifer ') can be used directly, while in Dojo, a package is used through define (['packageidentifier'], callback. In this case, node. js looks for the index. js or index. node module in the folder, while dojo looks for the Main. js module. Similarly, because the application runs under the dojo framework, the concept of the package is subject to the implementation of dojo.
If we understand the module loading as a classloader in Java, Dojo implements its own classloader to replace node. js's own behavior. Therefore, to run a dojo-based application on node. JS, the following command is used:
node <dojoroot>/dojo.js load=xxx
This command tells node. js to execute the dojo. js module and start the dojo framework. The subsequent parameter load = xxx tells dojo to execute the package XXX ). Here XXX is the entry point of your application. Because dojo has taken over the module management, the main. js module under the xxx package is run here.
With this understanding, we can further understand how to configure dojo to run a dojo-based application on node. js.
Run dojo on Node
The following is a simple example to show how to run a dojo-based program on node.
1. Introduce and configure dojo
We know that to introduce a framework such as Dojo on a browser, we first need to introduce the framework itself into the page, usually through the <SCRIPT> label introduction. At the same time, we can also pass parameters, for dojo, you can add attributes to the <SCRIPT> tag by using either of the following methods:
<script type=”text/javascript” src=”dojoroot/dojo/dojo.js” djConfig="isDebug:true"></script>
Here, djconfig is the configuration parameter passed to dojo. It sets the isdebug enabling status to output debugging information. Another way is to define a global variable named dojoconfig and configure it for dojo:
<script type=”text/javascript”> Var dojoConfig = { isDebug: true }; </script> <script type=”text/javascript” src=”dojoroot/dojo/dojo.js” ></script>
In node. JS, the method is similar. A node. js runable module is required to introduce dojo. For example, create a bootstrap. js file that contains the following content:
global.dojoConfig = { isDebug: true }; require('./dojo/dojo.js');
The method for defining global variables in node. JS is slightly different from that on the browser side. It defines global variables by adding an attribute to global. Then, use the require function to introduce dojo, which is equivalent to the <SCRIPT> tag in the HTML page. Therefore, in essence, this Bootstrap. js file is the dojo that contains configuration information. Directly use the following code to run dojo on node:
node <bootroot>/bootstrap.js
Of course, this line of command did not do anything, just ran dojo. Next let's look at how to run your own dojo program in Dojo.
2. Define the application portal
The global variable dojoconfig is used to configure dojo. In addition, you can define your own package. Each package may be an application or a class library. All packages are placed in the packages array:
global.dojoConfig = { isDebug: true, packages: [{ name: 'mynode' ,location: '../mynode' }] };
Here we define a package named mynode and specify its location. This is a location relative to <dojoroot>/dojo. To run this package, run the following command:
node <bootroot>/bootstrap.js load=mynode
Dojo obtains the package to be executed by using the load parameter. The main. js module under this package is executed and will be described below.
3. Execute the application
As described above, the package itself is not special, and it is a folder. When only one package is specified, instead of a specific module, dojo will automatically execute the main. js file under it. This main. js module is essentially no different from a common module, but this module generally only contains the application initialization logic, so as to start the application execution.
Now let's take a look at a simple "Hello World" example. Instead of using any dojo module, we only use define to define a module and print "Hello World ". Let's put the following content in Main. JS:
console.log(“Hello world”);
In this way, when you execute the commands mentioned above:
node <bootroot>/bootstrap.js load=mynode
In this way, we will see the output "Hello World" in the command line window ". Here we do not use any dojo module, but just let dojo find main. js and execute it. Let's take a look at how to rely on the dojo module to implement its own application logic.
In this example, we will use dojo to implement the DTL module of Django template language for String Conversion:
define(['dojox/dtl', 'dojox/dtl/Context'], function(dtl, DtlContext){ var template = new dtl.Template("Hello {{ place }}!"); var context = new DtlContext({ place: "World" }); console.log(template.render(context)); return null; });
As you can see, by using the functions provided by dojox. DTL, you can convert a DTL template-based string to HTML on the server side. Dojox. DTL implements the complete DTL syntax. Combined with the HTTP module of node. JS, it is easy to create a Web server. This is largely due to the DTL Implementation of dojo.
Postscript
Some people have predicted that node. js will replace php as the most popular server-side language. Whether you believe it or not, node. JS is rapidly evolving and gaining more and more attention. Some Web Servers Based on node. js can already be used for commercial purposes, such as http://expressjs.com. This makes JavaScript, a concise and elegant language, more and more attractive. As a powerful JavaScript framework, dojo has always been favored in enterprise applications. With its perfect support for node. JS, I believe it can play a greater role.
This article is first published on IBM developerworks.