Node. js entry-create a project and explain it in detail. node. js entry-level

Source: Internet
Author: User

Node. js entry-create a project and explain it in detail. node. js entry-level

After thinking for a long time, I always want to write something that is helpful to everyone. Today I will explain how to generate a project.

At present, the market generally requires a full stack of people ----- mean (mongo, express, angular, nodejs), which can be developed from the front end to the backend and the database. It sounds awesome.

In this article, we will talk about nodejs and the popular framework express4.X (because 3. I have not studied the Version X, and it is different from version 4. Besides, it has been around for a long time and is not usable.) I will refer to mongo in the following articles (oh, it should be called mongoose) as for angualr, I have studied it independently. I haven't used it together with the nodejs stream. Let's take a look at the actual situation.

This article will write a project for generation (ejs is used for the page, and jade wood has not been studied yet, so it cannot help everyone)

As we all know, a project must have many folders and files, so how can we quickly generate a development framework? The first is to use tools. I use webstorm, and the other is syntax, use commands to operate on the workspace, and then run the command express-e aTest (where-e refers to ejs, and aTest is the project name and the top folder name). In order to be visualized, we still use tools to generate.

1: A new project, all kinds of development started from here

2: select a node Project

3: select the version number and driver panel. if the version number is not changed, change the driver panel to ejs. Click OK.

Because nodejs has been installed locally, click cancel.

In this way, a nodejs project is generated. For example

Directory explanation:

App. js: Startup file, or entry file

Package. json: Stores project information and template dependencies. When a dependency module is added to dependencies, run npm install. nmp checks the package in the current directory. json, and automatically install all specified modules

Node_modules: stores the modules installed in package. json. After you add and install the dependent modules in package. json, store them in this folder.

Public: Stores image, css, js, and other files.

Routes: stores route files

Views: stores view files or template files.

Bin: stores executable files.


Open app. js

<span style="font-size:14px;">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 routes = require('./routes/index');var users = require('./routes/users');var app = express();// view engine setupapp.set('views', path.join(__dirname, 'views'));app.set('view engine', 'ejs');// uncomment after placing your favicon in /public//app.use(favicon(__dirname + '/public/favicon.ico'));app.use(logger('dev'));app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));app.use(cookieParser());app.use(express.static(path.join(__dirname, 'public')));app.use('/', routes);app.use('/users', users);// catch 404 and forward to error handlerapp.use(function(req, res, next) {  var err = new Error('Not Found');  err.status = 404;  next(err);});// error handlers// development error handler// will print stacktraceif (app.get('env') === 'development') {  app.use(function(err, req, res, next) {    res.status(err.status || 500);    res.render('error', {      message: err.message,      error: err    });  });}// production error handler// no stacktraces leaked to userapp.use(function(err, req, res, next) {  res.status(err.status || 500);  res.render('error', {    message: err.message,    error: {}  });});module.exports = app;</span>

Here, we load modules such as express and path through require (), as well as the index. js and users. js routing files under the routes folder. The following describes the meaning of each line of code.

(1) var app = express (): generate an express instance app.
(2) app. set ('view', path. join (_ dirname, 'view'): Set the views folder to the directory where the view files are stored, that is, where the template files are stored, where __dirname is the global variable, stores the directory where the script is currently being executed.
(3) app. set ('view engine ', 'ejs'): set the view template engine to ejs.
(4) app. use (favicon (_ dirname + '/public/favicon. ico'): Set/public/favicon. ico to favicon.
(5) app. use (logger ('dev'): load the Log Middleware.
(6) app. use (bodyParser. json (): loads the json-parsed middleware.
(7) app. use (bodyParser. urlencoded ({extended: false}): loads the middleware that parses the urlencoded Request body.
(8) app. use (cookieParser (): loads the middleware for parsing cookies.
(9) app. use (express. static (path. join (_ dirname, 'public'): Set the public folder to the directory where static files are stored.
(10) app. use ('/', routes); and app. use ('/users', users): route controller.
(11)

app.use(function(req, res, next) {    var err = new Error('Not Found');    err.status = 404;    next(err);});

Capture Error 404 and forward it to the error processor.
(12)

if (app.get('env') === 'development') {    app.use(function(err, req, res, next) {        res.status(err.status || 500);        res.render('error', {            message: err.message,            error: err        });    });}

The error processor in the development environment renders the error information into the error template and displays it in the browser.
(13)

app.use(function(err, req, res, next) {    res.status(err.status || 500);    res.render('error', {        message: err.message,        error: {}    });});

The error processor in the production environment renders the error information into the error template and displays it in the browser.
(14) module. exports = app: export the app instance to be called by other modules.

Next let's take a look at the bin/www file.

#!/usr/bin/env node/** * Module dependencies. */var app = require('../app');var debug = require('debug')('aTest:server');var http = require('http');/** * Get port from environment and store in Express. */var port = normalizePort(process.env.PORT || '3000');app.set('port', port);/** * Create HTTP server. */var server = http.createServer(app);/** * Listen on provided port, on all network interfaces. */server.listen(port);server.on('error', onError);server.on('listening', onListening);/** * Normalize a port into a number, string, or false. */function normalizePort(val) {  var port = parseInt(val, 10);  if (isNaN(port)) {    // named pipe    return val;  }  if (port >= 0) {    // port number    return port;  }  return false;}/** * Event listener for HTTP server "error" event. */function onError(error) {  if (error.syscall !== 'listen') {    throw error;  }  var bind = typeof port === 'string'    ? 'Pipe ' + port    : 'Port ' + port;  // handle specific listen errors with friendly messages  switch (error.code) {    case 'EACCES':      console.error(bind + ' requires elevated privileges');      process.exit(1);      break;    case 'EADDRINUSE':      console.error(bind + ' is already in use');      process.exit(1);      break;    default:      throw error;  }}/** * Event listener for HTTP server "listening" event. */function onListening() {  var addr = server.address();  var bind = typeof addr === 'string'    ? 'pipe ' + addr    : 'port ' + addr.port;  debug('Listening on ' + bind);}

Explanations:

(1 )#! /Usr/bin/env node: indicates the node executable file.
(2) var debug = require ('debug') ('blog '): Introduce the debug module and print the debugging log.
(3) var app = require ('../app'): Introduce the app instance we exported above.
(4) app. set ('Port', process. env. port | 3000): set the PORT number.
(5)

var server = app.listen(app.get('port'), function() {  debug('Express server listening on port ' + server.address().port);});

Start the project and listen to port 3000. Then, print Express server listening on port 3000.

Next let's take a look at the routes/index. js file:

var express = require('express');var router = express.Router();/* GET home page. */router.get('/', function(req, res, next) {  res.render('index', { title: 'Express' });});module.exports = router;

Generate a route instance to capture the GET request to access the homepage, export the route and load it through app. use ('/', routes) in app. js. In this way, when you access the home page, you will call res. render ('index', {title: 'express '}); render the views/index. ejs template and display it in the browser.


Let's look at the views/index. ejs file:

<!DOCTYPE html>

When rendering a template, we input a variable title value as an express string. The template engine replaces all <% = title %> with express, then, the rendered html is displayed in the browser, as shown in.


Through the above knowledge, we learned how to create a project and start it, and understand the general structure and operation process of the project. Next I will talk about routing...



























Zookeeper

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.