首页
学习
活动
专区
圈层
工具
发布

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脚本,内容如下:

Java代码

  1. #!/usr/bin/env node
  2. function a(){
  3. for(var i=0;i<10;i++){
  4. console.log('hello world'+i);
  5. }
  6. }
  7. //执行这个函数
  8. a();

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

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

Java代码

  1. //app.js
  2. var http = require('http');
  3. http.createServer(function(req, res) {
  4. //注意使用UTF-8防止乱码
  5. res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
  6. res.write('<h1>你好呀 Node.js</h1>');
  7. res.write("<script>alert('hello');</script>");
  8. res.end('Hello World
  9. ');
  10. }).listen(3000);
  11. 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的功能。

下一篇
举报
领券