Node demo项目搭建及打包

  1. 下载安装node.js,地址http://nodejs.cn/
  2. 打开cmd验证下是否安装成功

node demo项目搭建及打包

  1. 全局安装Express

node demo项目搭建及打包

  1. 全局安装express-generator

node demo项目搭建及打包

  1. 然后输入express 项目名

node demo项目搭建及打包

  1. 至此打开文件目录你会发现多了个myapp1的项目

node demo项目搭建及打包

  1. 我们在src 下新建个server.js这边使用的是websocket的demo
  2. var WebSocketServer = require('websocket').server;
    var
    http = require('http');

    var
    server = http.createServer(function(request, response) {
       
    // console.log((new Date()) + ' Received request for ' + request.url);
       
    response.writeHead(404);
       
    response.end();
    });
    const
    port = 8099
    server.listen(port, function() {
       
    // console.log((new Date()) + ' Server is listening on port ' + port);
    });

    wsServer = new WebSocketServer({
       
    httpServer: server,
       
    // You should not use autoAcceptConnections for production
        // applications, as it defeats all standard cross-origin protection
        // facilities built into the protocol and the browser.  You should
        // *always* verify the connection's origin and decide whether or not
        // to accept it.
       
    autoAcceptConnections: false
    });

    function
    originIsAllowed(origin) {
       
    // put logic here to detect whether the specified origin is allowed.
       
    return true;
    }

    wsServer.on('request', function(request) {
       
    if (!originIsAllowed(request.origin)) {
           
    // Make sure we only accept requests from an allowed origin
           
    request.reject();
           
    console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
            return;
       
    }

       
    var connection = request.accept('echo-protocol', request.origin);
       
    // console.log((new Date()) + ' Connection accepted.');
       
    connection.on('message', function(message) {
           
    if (message.type === 'utf8') {
               
    // console.log('Received Message: ' + message.utf8Data);
               
    connection.sendUTF(message.utf8Data);
           
    }
           
    else if (message.type === 'binary') {
               
    // console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
               
    connection.sendBytes(message.binaryData);
           
    }
        })
    ;
       
    connection.on('close', function(reasonCode, description) {
           
    // console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
       
    });
    });

那么该如何打包呢?

我们这边使用pkg进行打包

  1. 全局安装pkg,npm install -g pkg
  2. 我们修改package.json文件

node demo项目搭建及打包

  1. 执行pkg package.json

node demo项目搭建及打包

  1. 至此项目目录下会出现以下三个文件

node demo项目搭建及打包

直接运行就可以了

相关文章: