node js笔记1

1 在项目目录下 npm install xxxx,在项目目录下生成目录

2 全局安装 npm install -g express,加上参数g

3 查看npm的文档
   npm docs underscore
4 看bug
     npm edit underscore
5 package.json文件:
  {
  "name": "example02",
  "version": "0.0.1",
  "dependencies": {
    "underscore": "~1.2.1"
  }
}
  这里表明依赖的是underscore

   那么就可以在项目当前目录下,npm install了


6 简单的http服务器
   var http = require('http');
http.createServer(function (req, res) {
  res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

如果增加HTPP响应头
   var http = require('http');
http.createServer(function (req, res) {
  console.log(req);
  res.writeHead(200, {
'Content-Type': 'text/plain'
  });
  res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

  也可以重定向到其他网站,用的是301
  res.writeHead(301, {
    'Location': 'http://www.homestarrunner.com/sbsite/'
  });


7 安装express
    npm install -g express
在某个应用目录下安装exprss
    express express_sample
   cd express_sample&&npm install
   启动node app.js

8 node.js使用jade模板引擎
  jade无需使用html标记


修改views/index.jade文件
  extends layout

block content
  h1= title
  p Welcome to #{title}
   section#wrapper
    h2 Basic Structure
    section
      p
        span This is a span within a p within a section!

会自动添加标记翻译为:
 
9 - var name= "your name"
  -号定义后面的代码要被执行
    = 号告诉解析器要对代码进行运算
  
  - var name= "your name"
  hello #{name}
  则输出hello,your name

10 关于循环迭代
   extends layout

block content
  h1 Looping over an array
  - beatles = ['John', 'Paul', 'Ringo', 'George']
  ul
    each beatle in beatles
      li #{beatle}
输出<ul>
       <li>xxxx</li>
       <li>xxxx</li>
.................

11 if 语句
    - raining = true
  - if (raining)
    p It is raining. Take an umbrella!
  - else
    p No rain. Take the bike!

12 包含javascript
     script
    alert('Inline Javascript in Jade')


13 minxin功能
  
mixin users(users)
  ul
    each user in users
      li= user
- users = ['Tanya', 'Jose', 'Kim']
mixin users(users)
- more_users = ['Mark', 'Elena', 'Dave', 'Pete', 'Keiron']
mixin users(more_users)
    输出两组的<li> ....</li>

14 express路由
   在app.js中
  app.get('/about', function(req, res){
    res.send('Hello from the about route!');
});

post路由:
   app.post('/', function(req, res){
  res.send(req.body);
});

请求带参数:
  app.get('/users/:id', function(req, res){
  res.send('show content for user id ' + req.params.id);
});

15 模板渲染
   app.get('/', function(req, res){
  var user = {
    first_name: 'Barak',
    surname: 'Obama',
    address: 'The White House',
    facebook_friends: '10000000000000'
  };
  res.render('index.jade', { title: 'User', user: user  });
});

  将使用index.jade模板(views目录下的),渲染这个user

你可能感兴趣的:(Node js)