Learn Nodejs 02

(1)npm是什么

npm is the package manager for node

官方网站:https://www.npmjs.com/

npm上有很多优秀的nodejs包,来解决常见的一些问题,比如用node-mysql,就可以方便通过nodejs链接到mysql,进行数据库的操作

在开发过程往往会需要用到其他的包,使用npm就可以下载这些包来供程序调用

 

(2)npm的安装

(2.1)下载npm安装的shell脚本(install.sh)

 

脚本下载地址:https://www.npmjs.com/install.sh

 

 

(2.2)设置node.js的环境变量

 

#添加环境变量并使之生效(终端关闭后会失效),内容如下
#export PATH=$PATH:/database/nodejs/node-v0.12.7-linux-x64/bin

#建议修改.bashrc文件:

 

# vi /root/.bashrc
#在里面加入:
#export PATH=$PATH:/database/nodejs/node-v0.12.7-linux-x64/bin

 

 

(2.3)执行npm安装脚本

./install.sh
 
安装完成后这个路径
/database/nodejs/node-v0.12.7-linux-x64/lib/node_modules 
就会多一个npm
 
 
(3)npm安装express
 
(3.1)npm install express
[ root@localhost bin]# npm install express
[email protected] ../node_modules/express
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected]
├──  [email protected] ( [email protected])
├──  [email protected] ( [email protected])
├──  [email protected] ( [email protected],  [email protected])
├──  [email protected] ( [email protected],  [email protected])
├──  [email protected] ( [email protected],  [email protected])
├──  [email protected] ( [email protected],  [email protected],  [email protected],  [email protected],  [email protected])
└──  [email protected] ( [email protected])
 
(3.2)编写代码

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337);
console.log('Server running at http://202.102.83.169:1337/');
 
var express = require('express');
var app = express();
app.get('/hello.txt', function(req, res){
  res.send('express is ok');
});
 
var server = app.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);
});

(3.3)启动node.js
./node /database/nodejs/workspace/helloworld/first.js
进程启动
./node /database/nodejs/workspace/helloworld/first.js &
 
(3.4)查看端口占用的进程
fuser -n tcp 1337
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Learn Nodejs 02

猜你喜欢

转载自toknowme.iteye.com/blog/2228267