node.js在linux上使用教程
1.安装配置
-
sudo apt-get install nodejs npm
-
查看版本
node -v
npm -v
2.创建第一个应用
-
引入required模块 ,使用require指令来载入http模块,并将实例化的HTTP赋值给变量http,实例如下:
var http = require("http");
-
创建服务器,创建一个叫server.js文件,写入以下代码:
var http = require('http'); http.createServer(function (request, response) { // 发送 HTTP 头部 // HTTP 状态值: 200 : OK // 内容类型: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // 发送响应数据 "Hello World" response.end('Hello World\n'); }).listen(8888); // 终端打印如下信息 console.log('Server running at http://127.0.0.1:8888/')
使用node命令执行以上的代码:
node server.js
Server running at http://127.0.0.1:8888/
打开浏览器访问http://127.0.0.1:8888/ ,会看到“Hello World"网页