This article describes how to build a Node. js development environment in Linux. Node allows JavaScript programs to be explained and run in the local operating system environment. For more information, see
1. install node. js in Linux
Ubuntu:
sudo apt-get install nodejs npm
Centos:
yum install nodejs npm
For more detailed installation see: https://github.com/joyent/node/wiki/Installation
Npm is a package manager similar to Pear in PHP
2. start using node. js
Use the 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 common output command.
3. create an HTTP server
Understanding node. js architecture
The PHP architecture model is:
Browser -- HTTP server (apache, nginx) -- PHP interpreter
In node. js applications, node. js adopts the following methods:
Browser -- node. js architecture
Create an HTTP server: create an 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('
Node. js
'); 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 result.
This program calls the http Module provided by node. js, replies the same content to all Http requests, and listens to port 3000. After the script is run, it does not exit immediately. you must press ctro + c to stop it. this is because the listen function creates an event listener.
4. debug the script
After the node. js script is modified, you must stop the original program and run it again to see the changes.
Use the package manager to install the supervisor tool.
$ npm install -g supervisor
Later pass
$ supervisor app.js
To run the node. js program. it will detect program code changes and automatically restart the program.
Note: you must obtain the root permission during installation.