Thought for a very long time. Always want to write something to everyone has the merit of today's commentary build project.
Now the market generally need people full stack-----mean (mongo,express. Angular,nodejs), so that it can be developed from the front end to the backend as well as the database, sounds bull-roaring.
This article says Nodejs and the more popular frame express4. X version number (because the 3.X version number has not been studied.) And there is a certain difference from 4. Besides, 4 came out very long. It's not a good thing to do), and the following article will take MONGO (OH. Should be said to be mongoose) as for ANGUALR I have independent research. and Nodejs and the flow of put together with not done, or see the actual situation it.
This article will write a build project (the page with Ejs, the Jade Wood has not studied, can not hang the guys)
As we all know, a project must have very many directories and files. So how to build the development framework at high speed. Two ways, the first is to use the tool, I use the webstorm, the other is the syntax, with the command to work space, and then run the command express-e atest (Middle-e refers to Ejs. Atest is the project name. Also the top-level directory name), in order to be visualized. We still build with tools.
1:new a project, all kinds of development started here.
2: Choose Nodeproject
3: Select version and Drive panel, version does not change, drive panel changed to Ejs. Click OK
Because we have installed the Nodejs locally. So we clicked Cancel
In this way, a nodejsproject is generated. For example with
Folder explanation :
App.js: Boot file, or portal file
Package.json: Stores project information and template dependencies when a dependent module is added to the dependencies. Performing NPM INSTALL,NMP checks the Package.json under the current folder and proactively installs all of the specified modules
Node_modules: Store the module installed in the Package.json when you add the dependent module to the Package.json and install it in this directory
Public: Store image, CSS, JS and other files
Routes: Storing Routing files
Views: Store view files or template files.
Bin: Store 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 = Requir E (' 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/fa Vicon.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 Foun d '); Err.status = 404; Next (err);}); /error handlers//development error handler//would print Stacktraceif (app.geT (' env ') = = = ' Development ') {App.use (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 have loaded the Express, path module, and index under the routes directory via require (). JS and Users.js routing files. To explain the meaning of each line of code.
(1) var app = Express (): Generates an express instance app.
(2) App.set (' Views ', Path.join (__dirname): Set the Views folder as the folder where the view files are stored, that is, where the template files reside, __dirname are global variables, Stores the folder where the script that is currently running is located.
(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 as Favicon icon.
(5) App.use (Logger (' dev ')): Load log middleware.
(6) App.use (Bodyparser.json ()): Loads the middleware that parses the JSON.
(7) App.use (bodyparser.urlencoded ({extended:false})): Loads the middleware that parses the urlencoded request body.
(8) App.use (Cookieparser ()): Loads the middleware that parses the cookie.
(9) App.use (Express.static (Path.join (__dirname, ' Public ')): Set the public folder to the folder where the static files are stored.
(Ten) App.use ('/', routes), and App.use ('/users ', users): Routing controller.
(11)
app.use(function(req, res, next) { var err = new Error(‘Not Found‘); err.status = 404; next(err);});
The 404 error is captured and forwarded to the error handler.
(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 handler in the development environment renders the error message 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 handler in the production environment. Renders the error message to the bug template and displays it in the browser.
Module.exports = app: Export the app instance for other modules to invoke.
And then 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 I N Express. */var port = normalizeport (Process.env.PORT | | ' n '); App.set (' Port ', port);/** * Create HTTP server. */var Server = Http.createserver (APP),/** * Listen on provided port, in 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 + ' was 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);}
Explain:
(1) #!/usr/bin/env node: Indicates that node can run the file.
(2) var debug = require (' Debug ') (' blog '): Introduces the Debug module. Print Debug logs.
(3) var app = require ('.. /app '): Introduce the app instances we've 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 Project and listen for 3000 ports after successful printing of Express server listening on Port 3000.
Here's another 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 routing instance to capture a GET request for access to the home page, export the route and pass App.use ('/', routes) in App.js; Load.
This will call Res.render (' index ', {title: ' Express '}) when visiting the home page, render the Views/index.ejs template and display it in the browser.
Look at the Views/index.ejs file again:
<! DOCTYPE html>
When we render the template we pass in a variable with the title value of the Express string. The template engine replaces all <%= title%> with Express. The rendered HTML is then displayed to the browser, as you can see.
Through the above knowledge. we learned how to create a project and start it. Understand the general structure and operational processes of project. The next article is about routing.
。。
Nodejs Getting Started---Create project and explain in detail