在Linux系统中搭建Node.js开发环境的简单步骤讲解

2019-12-17,,,,

1. Linux安装node.js

ubuntu:

sudo apt-get install nodejs npm

centos:

yum install nodejs npm

更详细的安装参见:https://github.com/joyent/node/wiki/Installation
npm为类似PHP中Pear的包管理器

2. 开始使用node.js

用文本编辑器新建hello.js写入以下内容

console.log('hello world');

打开命令行输入

$ node hello.js

你会看到输出  

 $ hello world

    console.log是最常用的输出指令

3. 建立HTTP服务器

理解node.js架构
像PHP的架构模型为:
    浏览器--》HTTP服务器(apache、nginx)--》PHP解释器

而在node.js应用中,node.js采用:
    浏览器--》node.js这种架构

创建HTTP服务器:新建一个app.js文件,内容如下:

var http = require('http');
http.createServer(function(req, res){
  res.writeHead(200,{'Content-Type': 'text/html'});
  res.write('</pre>
<h1>node.js</h1>
<pre>');
  res.end('
hello world
 
');
}).listen(3000);
console.log("http server is listening at port 3000.");

运行

$ node app.js

打开浏览器打开http://127.0.0.1:3000查看结果

该程序调用了node.js提供的http模块,对所有的Http请求答复同样的内容并监听3000端口。运行这个脚本后不会立刻退出,必须按下ctro+c才会停止,这是因为listen函数创建了事件监听器。

4. 调试脚本

node.js脚本修改后,必须停止原程序,重新运行,才能看到变化。
用包管理器安装supervisor工具。

$ npm install -g supervisor

以后通过

$ supervisor app.js

來运行node.js程序,它会检测程序代码变化,自动重启程序。
注意:安装时需要获得root权限。

您可能感兴趣的文章:

  • 跟我学Nodejs(一)--- Node.js简介及安装开发环境
  • Node.js的环境安装配置(使用nvm方式)
  • 通过node-mysql搭建Windows+Node.js+MySQL环境的教程
  • Windows8下搭建Node.js开发环境教程
  • Nginx+SSL+Node.js运行环境配置教程
  • win7下安装配置node.js+express开发环境
  • node.js基础知识小结

《在Linux系统中搭建Node.js开发环境的简单步骤讲解.doc》

下载本文的Word格式文档,以方便收藏与打印。