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

前端技术 2023/09/01 JavaScript

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权限。

本文地址:https://www.stayed.cn/item/1672

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。