NodeJs错误:写EPIPE http unix套接字域LXD API

时间:2015-10-19 21:54:07

标签: node.js api sockets epipe lxd

整个想法是在unix套接字上使用LXD RESTful API进行本地操作。对于每个有错误的2或3,以下代码运行良好一次。我不知道是否与node.js有关或与lxd api有关。

输出错误

请求问题:写EPIPE {[错误:写EPIPE]   代码:'EPIPE',   错误:'EPIPE',   系统调用:'写',   地址:undefined}

代码:

/*
Adapted from 
http://rapiddg.com/blog/calling-rest-api-nodejs-script
*/
var querystring = require('querystring');
var http = require('http'), req, response;

var socketUSD='/var/lib/lxd/unix.socket';

function RestConsume(){ };

RestConsume.prototype._doRequest_=function(httpMethod,pathAPI,data,fnCallBack){
        var dataString = JSON.stringify(data);
        var headers = {};

        if (httpMethod==='GET'){
            pathAPI+='?'+querystring.stringify(data);

        }else{
            headers = {
              'Content-Type': 'application/json',
              'Content-Length': dataString.length
            };
        }
        var options = {
                socketPath: socketUSD,
                path: pathAPI,
                method: httpMethod,
                headers: headers
            };

        var req=http.request(options, function (res){
            res.setEncoding('utf-8');

            var resultString="";

            res.on('data',function(data){
                resultString +=data;
            });//end res.on('data')//

            res.on('end',function(){
                console.log(resultString);
                var responseObject = JSON.parse(resultString);
                fnCallBack(resultString);
            });
        });

        req.write(dataString);
        req.end();
        req.on('error', function(e) {
            console.log('Haciendo '+httpMethod);
          console.log('problem with request: ' + e.message);
          console.log(e);
        });
};
RestConsume.prototype.doGet=function(pathAPI,data,fnCallBack){
        return this._doRequest_('GET',pathAPI,data,fnCallBack);
};
RestConsume.prototype.doPost=function(pathAPI,data,fnCallBack){
        this._doRequest_('POST',pathAPI,data,fnCallBack);
};
RestConsume.prototype.doPut=function(pathAPI,data,fnCallBack){
        this._doRequest_('PUT',pathAPI,data,fnCallBack);
};
RestConsume.prototype.doDelete=function(pathAPI,data,fnCallBack){
        return this._doRequest_('DELETE',pathAPI,data,fnCallBack);
};
var obj=new RestConsume();
obj.doGet("/1.0/containers/pc01/logs",{},function(data) {
    console.log('get Respuesta:\r\n' + data);
  });

1 个答案:

答案 0 :(得分:1)

修正:use the documentation

更准确地说是:

Resource

现在,代码就像魅力一样。