First, equipment
My personal PC environment is UBUNTU14+JDK7, so the following steps and problems are based on this and generated.
Ii. installation of Nodejs and NPM
This installation process has many tutorials on the web, which is not detailed here.
$ sudo apt-get install python $ sudo apt-get install build-essential $ sudo apt-get install gcc $ sudo apt-get install g++ $ sudo apt-get install nodejs$ sudo apt-get install NPM
View the Nodejs version, many of the online tutorials are written:
Node-v
However, the node command cannot find an exception, and the following command is used to perform the success:
Nodejs-v
Terminal display:
v0.10.25
After testing, Ubuntu under Nodejs command is Nodejs, while the Windows platform is node.
View NPM Version Yes
Npm-v 1.3.10
Third, use NPM to install Supervisor tools and express frame
1, Supervisor
Brief introduction:
When developing an HTTP application implemented by node. JS, you will find that no matter which part of your code you modify, you must terminate node. js and rerun it to work. This is because node. js only parses the script file the first time it is referenced to a part, and then accesses the memory directly, avoiding repeated loading. This design of node. JS, while improving performance, is not conducive to development debugging because we always want to see the effect as soon as we change it, rather than terminating the process and restarting it every time.
Supervisor can help you implement this feature by monitoring your code changes and automatically restarting node. js.
A) global installation (My choice)
NPM Install SUPERVISOR-GD
b) installed under the current folder
NPM Install Supervisor
After the installation is successful, the command line prompts NPM info OK
-G represents the installation to the Lib in Node_path, and the-D represents the installation of the dependency kit. If you do not have-G, the current directory will be installed (a Node_modules folder will be created).
Use the following command to view the help documentation for supervisor,
Terminal display:
/usr/bin/env:node: No file or directory
After finding out, NPM found that when installing the module, the source code and execution files will be separated.
/usr/local/lib/node_modules Source Directory/usr/local/bin Execute file directory
Note: This is not the same as most of the online tutorial, the online tutorial says that the source code and execution files are placed in the/usr/local/lib/node_modules directory, it is estimated that the NPM version of the different reasons.
Locate and view the Supervisor execution file:
#!/usr/bin/env node var path = require ("path") , FS = require ("FS") , args = Process.argv.slice (1) var arg, base; Do arg = Args.shift (); while (Fs.realpathsync (ARG)!== __filename && (base = Path.basename (ARG))!== "Node-supervisor" && Amp Base!== "Supervisor" && base!== "Supervisor.js") require ("./supervisor"). Run (args)
Seeing supervisor's introduction, it is easy to know that the main function of this small module is two:
1. Close the project that is being executed
2. Start the previously closed project
The error reported here is that node was not found, and it was clear that the first line of the execution file used the command!/usr/bin/env node, recalling the previous view of the Nodejs version of the command . The project started with the command Nodejs of Nodejs itself,
Therefore, this line is modified as follows to try, the problem is resolved.
#!/usr/bin/env Nodejs
The terminal displays Help for supervisor as follows:
Node Supervisor is used to restart programs when they crash. It can also is used to restart programs when a *.js file changes. usage:supervisor [Options] <program> Supervisor [Options]-<program> [args ...] Required: <program> to run. Options:-w|--watch <watchItems> A comma-delimited List of folders or JS files to watch for changes. When a-to-a JS file occurs, reload the program Default is '. ' -i|--ignore <ignoreItems> A comma-delimited List of folders to ignore for changes. No Default-p|--poll-interval <milliseconds> How often to poll watched files for changes. Defaults to Node default. -e|--extensions <extensions> specific file extensions to watch on addition to defaults. Used when--watch option includes folders Default was ' Node,js '-x|--exec <executable> the executable that Runs the specified program. Default is ' node '--debug Start node With--debug flag. --debug-brk[=port] Start node with--debug-brk[=port] flag. --harmony Start node with--harmony flag. -n|--no-restart-on error|exit Don ' t automatically restart the supervised program if it ends. Supervisor'll wait for a change in the source files. If "Error", an exit code of 0 would still restart. If "Exit", no restart regardless of exit code. --force-watch use Fs.watch instead of fs.watchfile. This is useful if you see a high CPU load in a Windows machine. -h|--help|-? Display these usage instructions. -q|--quiet Suppress debug messages-v|--verbose Show extra debug Messages Examples:supervisor myapp.js Supe Rvisor myapp.coffee supervisor-w scripts-e myext-x myrunner MyApp Supervisor--server.js-h host-p Port
Note: Depending on the help document, the command to view Supervisor is supervisor-v. The V in the command is uppercase, and during installation I find the lower case in Windows OK, but in my UBUNTU14 environment it must be uppercase.
2. Express
A) global installation (My choice)
NPM Install EXPRESS-GD
b) installed under the current folder
NPM Install Express
After the installation, express and supervisor, there is a NODEJS command does not meet the problem, the same way to find the execution of the file to modify this command.
After installing Express, if the version is 4.0 and above, also install another module, express to use.
sudo npm install-g express-generator
Iv. establishment and implementation of the project 1. Create a new project called Test 2, using the Express framework
CD to the parent directory of the test directory, execute the following command
EXPRESS-E Test
When you're done, go back to the project directory to see:
Node_modules, store all project dependent libraries. Package.json, Project dependent configuration and developer Information App.js, program startup file public, static file (css,js,img) routes, routing file (C,controller in MVC) views, paging file (ejs template) Bin, which holds the default startup script
Package.json:
{ "name": "Pcrm", "version": "0.0.1", " private": True, "scripts": { "start": "Node./bin/www" }, "dependencies": { "Express": "~4.2.0", "Static-favicon": "~1.0.0", "Morgan": "~1.0.0", "Cookie-parser": "~1.0.1", "Body-parser": "~1.0.0", "Debug": "~0.7.4", "Ejs": "~0.8.5" } }
App.js:
var express = require (' Express '), var path = require (' path '), var favicon = require (' Static-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 '); App.use (Favicon ()); App.use (Logger (' dev ')); App.use (Bodyparser.json ()); App.use (bodyparser.urlencoded ()); 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//would 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.statu s | | 500); Res.render (' error ', {message:err.message, error: {}}); Module.exports = app;
Bin/www:
#!/usr/bin/env Nodevar debug = require (' Debug ') (' Pcrm '); var app = require ('.. /app '); App.set (' Port ', Process.env.PORT | | 3000); var server = App.listen (app.get (' Port '), function () { debug (' Express Server listening on port ' + server.address (). por t);});
3. Implementation
CD to test directory
Execution Method 1:
NPM start
Terminal Display Exception:
> [email Protected] start/home/benben/workspace/test> node/bin/www sh:1: Node:not foundnpm err! Weird error 127NPM WARN This failure might being due to the use of legacy binary "node" NPM WARN for further explanations, ple ASE Read/usr/share/doc/nodejs/readme. Debian NPM err! Not OK Code 0
or the node command issue, modify the Package.json file in the
"Start": "Node./bin/www" is " start": "Nodejs./bin/www"
In the Bin/www file
#!/usr/bin/env node for #!/usr/bin/env Nodejs
Successful execution
What is NPM? Most Java programmers have used maven. The function of NPM, like Maven, is a NODEJS package management tool that you can use to download packages, View files and other features the application created with Express is a NODEJS package that complies with the COMMONJS specification when NPM executes the Package.json file that reads the current directory, which is why the bug above me is executing NPM Start is actually the command that corresponds to the Start property in the object that executes the script in Package.json.
So in fact, if the start in Package.json is changed to test or another string, then you hit NPM test/or other on the terminal, the program will still run.
In fact, Package.json is a configuration file, just the XML format we used before, but in Nodejs json can be, simple and easy to understand. From Package.json we can see that NPM start actually executes the./bin/www inside is to create a server and listen to Port 3000, so we can access the application by entering "localhost:3000" in the browser.
Execution Method 2:
NPM Start is a script in the enabled/bin/www file
If you want to start the service with Nodejs, you can add the following code in App.js
Note: The above statement has to be added to Module.exports = app;
Nodejs App.js
Get the same results.
Execution Method 3:
Perform a hot deployment with supervisor for easy commissioning
Supervisor App.js
Terminal Display Exception:
Running node-supervisor with program ' app.js ' --watch '. ' --extensions ' Node,js ' --exec ' node ' starting child process with ' node App.js ' EXECVP (): No such file or Directorywatch ing directory '/HOME/BENBEN/WORKSPACE/PCRM ' for changes. events.js:72 throw er;//unhandled ' error ' event ^error:spawn ENOENT at errnoexception (child_process.js : 988:11) at process.childprocess._handle.onexit (child_process.js:779:34)
The process here is not detailed, the focus is--exec ' node ' This, will find Supervisor execution or node command, rather than Nodejs. Modify the Supervisor.js file in the Supervisor source file directory
if (!executor) { executor = (Programext = = = "Coffee" | | programext = = "Litcoffee")? "Coffee": "Node"; }
For
if (!executor) { executor = (Programext = = = "Coffee" | | programext = = "Litcoffee")? "Coffee": "Nodejs"; }
Once again, the Nodejs will restart automatically after the project is modified.
V. The choice of IDE is nodeclipse, but it is not perfect. So choose Webstorm.
With regard to the use of IDE and NODEJS, the article will be recorded later in the process of use.
Nodejs the first day of the environment and the problems that arise