Category: NodeJS

  • npm taobao

    设置淘宝源

    npm config set registry https://registry.npm.taobao.org 
    

    检查确认

    cat ~/.npmrc 
    registry=https://registry.npm.taobao.org
    
  • nodejs

    node 04
    Modules
    Semantic Versioning
    version patch
        “connect”: “~2.2.1”,
        “underscore”: “~1.3.3”
    node 03
    streams
    curl –upload-file abc.jpg http://localhost:3000
    node 01
    fs.readFileSync
    fs.readFile(‘/etc/hosts’, function(){});
    setTimeout(function(){ console.log(“here we go”)}, 5000); // 等 5000ms 再运行 function
    non-blocking
    epxress 05
    route instances
    app.route()
    chaining function
    single application file is too long
    extracting routes to modules
    var router = express.Router();
    set router as a express module
    module.exports = router;
    var router = express.Router();
    router.route(‘/’);
    app.use(‘/cities’, router);
    router.route(‘/’)
      .get(function (request, response) {
        if(request.query.search){
          response.json(citySearch(request.query.search));
        }else{
          response.json(cities);
        }
      })
      .post(parseUrlencoded, function (request, response) {
        if(request.body.description.length > 4){
          var city = createCity(request.body.name, request.body.description);
          response.status(201).json(city);
        }else{
          response.status(400).json(‘Invalid City’);
        }
      });
    router.route(‘/:name’)
      .get(function (request, response) {
        var cityInfo = cities[request.cityName];
        if(cityInfo){
          response.json(cityInfo);
        }else{
          response.status(404).json(“City not found”);
        }
      })
      .delete(function (request, response) {
        if(cities[request.cityName]){
          delete cities[request.cityName];
          response.sendStatus(200);
        }else{
          response.sendStatus(404);
        }
      });
    What function would you call to match all HTTP verbs?
    app.all()
    express 04
    post & delete
    body-parser
    app.delete(‘/blocks/:name’, function(request, response){});
    response.sendStatus(200);
    express 03
    handle routes
    response.json();
    /blocks?limit=1
    use request.query to access query strings
    blocks.slice(1, 3)  from 1 , 3 items
    response.status(404).json(‘No description found for ‘ + request.params.name)
    maps placeholders to callback functions, and is commonly used for running pre-conditions on Dynamic Routes
    app.param(‘name’, function(request, response, next){
    });
    javascript
    array ->   blocks = [‘Fixed’, ‘Movable’, ‘Rotating’];
    object ->  blocks = {
        ‘Fixed’: ‘description 1’,
        ‘Movable’: ‘description 2’,
        ‘Rotating’: ‘description 3’
    }
    for object , use Object.keys(blocks) get all keys of objects.
    express 02
    response.sendFile(__dirname + ‘/public/index.html’);
    express 的 static middleware
    middleware 用于检验,认证,数据解析
    app.use(express.static(‘public’));
    当调用一个 middleware ,可以加一个 next 调用下一个 middleware
    app.use(function(request, response, next) {
        next();
    });
    到最后一个 middleware,没有 next 则响应一个 done
    app.use(function(request, response, next){
        response.send(‘done!’);
    });
    express 使用 ajax 返回
    express 01
    安装 node 并指定版本
    npm install [email protected]
    response.send();
    blocks = [“a”, “b”, “c”];
    response.send(blocks);
    curl 查看 header 会发现自动解析成 json
    等同于
    response.json(blocks);
    302跳转
    response.redirect(‘/parts’);
    301跳转
    response.redirect(301, ‘/parts’);
  • node数据类型

    ➜  ~  node
    > var a = 1;
    undefined
    > typeof a
    'number'
    > var b = {}
    undefined
    > typeof b
    'object'
    > var c = function() {};
    undefined
    > typeof c
    'function'
    > var d = '';
    undefined
    > typeof d
    'string'
    
  • npm使用淘宝的registry

    遇到过 forever 装不上的情况

    /usr/bin/npm install forever -g
    
    701 error Error: shasum check failed for /root/tmp/npm-5826-Ev6S_4GZ/1438247556786-0.7053809177596122/tmp.tgz
    701 error Expected: 4353b88b7131797fb5520e39eba263df5863cba3
    701 error Actual:   28322c7853c55e33081b19337d4e5359b8cceaae
    701 error     at /usr/lib/node_modules/sha/index.js:38:8

    换成淘宝的registry后正常。

    npm config set registry http://registry.npm.taobao.org/
  • nodejs-forever

    node.js的forever可保证进程挂掉之后重启,保证高可用

    Monitors the script specified in the current process or as a daemon

    [Daemon]                                                                                                                                                                     

      The forever process will run as a daemon which will make the target process start

      in the background. This is extremely useful for remote starting simple node.js scripts

      without using nohup. It is recommended to run start with -o -l, & -e.

      ex. forever start -l forever.log -o out.log -e err.log my-daemon.js

    常用动作有

    start Start SCRIPT as a daemon
    stop Stop the daemon SCRIPT
    stopall Stop all running forever scripts
    restart Restart the daemon SCRIPT
    restartall Restart all running forever scripts
    list List all running forever scripts
    config Lists all forever user configuration
    set Sets the specified forever config
    clear Clears the specified forever config
    logs Lists log files for all forever processes
    logs <script|index> Tails the logs for <script|index>
    columns add
    Adds the specified column to the output in `forever list`
    columns rm
    Removed the specified column from the output in `forever list`
    columns set Set all columns for the output in `forever list`
    columns reset Resets all columns to defaults for the output in `forever list`
    cleanlogs [CAREFUL] Deletes all historical forever log files

    例子:

    查看被forever启动的进程

    forever list

    重启具体某一个脚本,如果不知道绝对路径,forever会自动匹配重启

    forever restart myscript.js

    –sourceDir指定js脚本位置

    forever stop --sourceDir=/data/nodejs/ start.js

    -l 指定log所在位置, -e 指定错误日志,-o指console的输出,-a 追加的方式,平时使用时最好把-l, -e, -o全用上。

    forever start -l /var/log/nodejs/log -e /var/log/nodejs/error -o /var/log/nodejs/out.log -a --sourceDir=/data/nodejs start.js
  • ubuntu安装配置nodejs

    安装nodejs,npm

    apt-get install nodejs
    apt-get install npm

    编写hello.js

    var http = require('http');
    http.createServer(
    function(req, res){
    res.writeHead(200, {'Content-Type':'text/plain'});
    res.end('hello node.js');
    }
    ).listen(8124,"127.0.0.1");
    console.log('Server running at http://127.0.0.1:8124/');

    运行

    node hello.js

    打开浏览器即可看到

    hello node.js