您的位置:首页 > Web前端 > Node.js

macOS下搭建Node.js环境

2017-02-14 21:08 323 查看

1.安装Homebrew

$:ruby -e "$(curl -fsSl http://raw.githubusercontent.com/Homebred/install/master/install);"[/code] 

2.安装Node

$:brew install node


需要稍微等待一会,看到如下界面即安装成功



3.查看Node版本:

$:node -v


测试:

在桌面新建一个test.js的文件

$:cd Desktop/
$:touch test.js
$:vim test.js


写入以下代码

var http = require('http')
var data = {name:'stevin',location:'Beijing'};
var srv = http.createServer(function(req,res) {
res.writeHead(200,{'Content-Type':'application/json'});
res.end(JSON.stringify(data));
});

srv.listen(8080,function(){
console.log('listening on localhost:8080');
});


编写完后保存并且退出
:wq
编辑状态, 然后执行
$:node Desktop/test.js
运行,显示:

listening on localhost:8080


第一次系统会询问是否同意接入网络, 点击同意即可,然后在浏览器地址栏键入:localhost:8080, 即可显示数据

{"name":"stevin","location":"Beijing"}


ctrl+c
结束运行

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息