Nodejs笔记(二)

上篇已经介绍了关于Nodejs的背景,优缺点,下载和安装,本篇来看下如何简单的使用nodejs:
(1)执行node -h查看nodejs的命令行文档
比较常用的有:
node -v 查看版本
node -e  "console.log('helloworld')"  执行eval一个字符串的js脚本
node hello.js  执行一个js脚本
node -i 进入一个交互式的命令行

(2)执行npm -h查看npm的命令行文档
比较常用的有:
npm install npm@lastest  局部安装一个插件
npm -g  install  npm@lastest-2 全局安装一个插件
npm -v 查看npm的版本
npm -g uninstall sax 全局卸载
npm uninstall sax 局部卸载

(3)打印nodejs的helloworld
写一个hello.js脚本,内容如下:

#!/usr/bin/env node

function a(){
for(var i=0;i<10;i++){
console.log('hello world'+i);
}
}
//执行这个函数
a();



执行 node hello.js后,shell终端打印:






(4)用nodejs实现第一个简单的web服务app.js
功能:实现一个web服务器,通过http:ip:3000能够访问,代码如下,非常简洁:

 //app.js
var http = require('http');
http.createServer(function(req, res) {
//注意使用UTF-8防止乱码
res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
res.write('<h1>你好呀 Node.js</h1>');
res.write("<script>alert('hello');</script>");
res.end('Hello World
');
}).listen(3000);
console.log("HTTP server is listening at port 3000.");



执行node app.js,随便找一台机器,使用火狐访问:








(5)使用命令行编程效率比较低,推荐使用Intellij IDEA非常不错的一款的IDE,支持许多种编程语言,包括Java,Python,Golang,PHP等

打开IDEA点击File => Setting => Plugins =>Browse Repositories => 在搜索框输入nodejs,找到插件并安装,安装完成后重启IDEA即可
支持语法高亮,自动提示,debug等非常nice的功能。






有什么问题 可以扫码关注微信公众号:我是攻城师(woshigcs),在后台留言咨询。
技术债不能欠,健康债更不能欠, 求道之路,我们同行。







猜你喜欢

转载自qindongliang.iteye.com/blog/2292945