1. Linux installation node.js
ubuntu:
sudo apt-get install nodejs npm
centos:
yum install nodejs npm
For more detailed installation, please see: https://github.com/joyent/node/wiki/Installation
npm is a package manager similar to Pear in PHP
2. Start using node.js
Use a text editor to create hello.js and write the following content
console.log('hello world');
Open command line input
$ node hello.js
You will see the output
$ hello world
console.log is the most commonly used output command
3. Establish HTTP server
Understand node.js architecture
The architectural model of PHP is:
Browser--"HTTP server (apache, nginx)--"PHP interpreter
In node.js applications, node.js uses:
Browser--》node.js architecture
Create HTTP server: Create a new app.js file with the following content:
var http = require('http'); http.createServer(function(req, res){ res.writeHead(200,{'Content-Type': 'text/html'}); res.write('
'); res.end(' hello world '); }).listen(3000); console.log("http server is listening at port 3000.");
Run
$ node app.js
Open the browser and open http://127.0.0.1:3000 to view the results
This program calls the http module provided by node.js, replies with the same content to all Http requests and listens to port 3000. After running this script, it will not exit immediately. You must press Ctro+C to stop. This is because the listen function creates an event listener.
4. Debugging script
After modifying the node.js script, you must stop the original program and re-run it to see the changes.
Install the supervisor tool using a package manager.
$ npm install -g supervisor
Pass later
$ supervisor app.js
to run the node.js program, it will detect program code changes and automatically restart the program.
Note: Root permissions are required during installation.