Preface
It is an event-driven I/O server-side JavaScript environment, which can also be understood as JavaScript running on the server side. As a programming language, JS runs in a virtual machine called the JS runtime, and in terms of I/O functions, JS relies more on the host environment. Generally, the host environment we encounter is mainly a browser, which is a high-speed JavaScript interpreter running on the server side.
Recently, I encountered a small website that needed to build a simple web server. I originally wanted to use SpringMVC to solve it, but Spring's philosophy is profound and profound, and I am not knowledgeable and cannot ship it quickly. Therefore, I decided to try it. Here I will briefly introduce how to quickly start a simple and easy-to-use Web Server. The development environment I'm using here is Elementary OS based on Ubuntu 14.04.
1. Preparation
1.1 Installing the NodeJS environment and npm module manager
sudo apt-get install nodejs sudo apt-get install npm
npm is an excellent Node module manager that helps us solve dependency management transactions in many third-party code bases during development.
1.2 Setting up npm proxy
If no additional measures are taken in advance, it will inevitably be very slow when you use npm to download the NodeJs module you need from the network, and it will even fail due to timeout. I won’t talk about the specific reasons. It is recommended to use Taobao’s npm mirror, and the problem will be solved.
- Open ~/.npmrc file
- enter
registry =
- Save Exit
Note that if you have set up a global wall penetration but npm is still very slow, you can try to continue adding it in the ~/.npmrc file
- proxy=false
2. Use Express Generator to build a development environment
Express is the most popular web development framework currently, which can quickly build a fully functional website.
Express Generator is Express's application generator tool that quickly creates a complete project file directory.
2.1 Install Express Generator
$ npm install express-generator -g
2.2 Create Express Application
express --view=pug NodeApp
Here the view parameter is used to preset the template engine used in development. More parameters are as follows
express -h Usage: express [options] [dir] Options: -h, --help output usage information --version output the version number -e, --ejs add ejs engine support --pug add pug engine support --hbs add handlebars engine support -H, --hogan add engine support -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory
2.3 Solve module dependencies
Enter the NodeApp folder you just created and you can see a file inside that defines the various modules required for this project, as well as the project configuration information (such as name, version, license and other metadata). npm can manage project modules based on it.
Open it and you can see the contents below
{ "name": "NodeApp", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.16.0", "cookie-parser": "~1.4.3", "debug": "~2.6.0", "express": "~4.14.1", "morgan": "~1.7.0", "pug": "~2.0.0-beta10", "serve-favicon": "~2.3.2" } }
Now execute the npm command in the terminal to solve the module dependency. npm will download the corresponding module according to the content of the file. Of course, this step cannot be executed without setting the wall-through measures.
npm intsall
3. Start the server for the first time
Basically, the configuration and basic logic code that should be available are all done by Express Generator, so we can actually start the server with one line of commands.
Execute the following command
npm start
Visit localhost:3000 to see the Express welcome page.
4. Set the access address
You can see that there is a file in the file directory I created before. In fact, it acts as the main function in a project, using a lot of Express middleware and Express syntax, which I will not describe one by one here.
In an actual production environment, we need to set the external access port ourselves, such as accessing our server through port 80 of Http, so we can use the file" = app;"
Add the following code before the statement
var server = (80, "0.0.0.0", function () { ("Server IP Address:" + ()); var host = ().address; var port = ().port; ("The application has been started, the access address is http://%s:%s", host, port) });
To briefly explain here, 80 means that our server program will listen to the local port 80, and 0.0.0.0 means that both local and external access requests will be processed by our server program.
At the same time, after starting the server, we can also see the IP address of the current host and the access address accepted by the server program in the terminal.
5. Set the index page content
Until here, when we visit the localhost address, we will see the Express default welcome page. So how do we return to a page of our own? For example, we now have a page, and we need to return this html page when the user accesses localhost, and the issue of static files is not considered for the time being.
You can enter the file, it should now look like this,
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup ('views', (__dirname, 'views')); ('view engine', 'pug'); // uncomment after placing your favicon in /public //(favicon((__dirname, 'public', ''))); (logger('dev')); (()); (({ extended: false })); (cookieParser()); (((__dirname, 'public'))); ('/', index); ('/users', users); // catch 404 and forward to error handler (function(req, res, next) { var err = new Error('Not Found'); = 404; next(err); }); // error handler (function(err, req, res, next) { // set locals, only providing error in development = ; = ('env') === 'development' ? err : {}; // render the error page ( || 500); ('error'); }); var server = (80, "0.0.0.0", function () { ("Server IP Address:" + ()); var host = ().address; var port = ().port; ("The application has been started, the access address is http://%s:%s", host, port) }); = app;
One of the sentences is like this
('/', index);
Its meaning is that when the server program captures a request with the access path "/", the index middleware performs corresponding processing.
Here is a good description of Express middleware online
Simply put, middleware is a function that handles HTTP requests. Its biggest feature is that one middleware is processed and then passed to the next middleware. During the runtime of the App instance, a series of middleware will be called. Each middleware can receive three parameters from the App instance, namely the request object (representing HTTP request), the response object (representing HTTP response), and the next callback function (representing the next middleware). Each middleware can process HTTP requests (request objects) and decide whether to call the next method and pass the request object to the next middleware.
So where does the index middleware come from?
var index = require('./routes/index');
So we can go to the routes folder to view the index file, it should look like this
var express = require('express'); var router = (); /* GET home page. */ ('/', function(req, res, next) { ('index', { title: 'Express' }); }); = router;
As can be seen from the code comments, this is the logical code of the Express welcome page mentioned above. Of course, it uses the knowledge of the template engine. We will not introduce it in detail, but will directly and simply and roughly implement our needs.
First, we save the page to the public/html folder in the file directory (if we don’t create it yourself), and then we return to the html page in the routes/index file, where we will use the file reading and writing method.
var path = require('path'); (('public/html/'));
The path variable is a variable in Express.
The method can convert the passed-in relative address into absolute address. This involves knowledge about the NodeJs file path and will not be introduced in detail.
The res variable represents the server's return object for this request, so here is equivalent to the file we return to the client in the public/html/ file.
Restart the program, visit localhost, and you can see it.
6. Set static file path
For static files such as JS and CSS, they are placed in the public folder in Express. When Express encounters requests for static files, it will read from pulic and return the corresponding file.
The statement that sets this path is actually in
(((__dirname, 'public')));
Therefore, if the project requires it, you can also modify this journey by yourself.
7. Run the server in the background
Before, our terminal was runningnpm start
When you are , you should see that all log statements accessing print are displayed in the terminal. If we close the terminal, the program will also stop accordingly. How to run our server program in the background and write all the printed log statements to a special log file? Here you need to use the nohup command and redirector of Linux.
npm start 1> log 2> error
> is a redirector under linux. > Will rewrite the target file, that is, the original content of the target file is not saved, and if you use >>, the content will be attached after the target file.
In Linux, a program can produce output on any of several numbered file streams. However, we must regard the first three of these file streams as standard input, output and error, and the shell internally references them as file descriptors 0, 1 and 2. Therefore, the meaning of this statement is to redirect the standard output to the log file in the current directory and redirect the error output to the error file in the current directory.
However, this only solves the problem of transferring and outputting output information, and the program is still running in the terminal. This can be achieved using the nohup command under Linux, using the following
nohup npm start 1> log 2> error &
Don't forget the last & symbol.
Be careful when running jobs in the background: do not place commands that require user interaction in the background, because your machine will be waiting there stupidly. However, running the job in the background will also output the results to the screen, interfering with your work, so you need the help of the redirector.
Subsequent
Now a simple web server is built. This is just the first part of a web server. Later development requires in-depth learning and use of NodeJs and Express.
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.