在node.js服务器中从文件移动到json数组

时间:2015-04-17 14:32:33

标签: javascript json node.js

实际上我已经构建了这个代码,它从node.js服务器上的调用中返回一个client.html文件。

fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
  console.log(err);
  res.writeHead(500);
  return res.end('Error loading client.html');
}
res.writeHead(
              200,
                {
                    "access-control-allow-origin": origin,
                    "content-length": data.length
                }
              );
res.end(data);
});

我正在尝试更改我的代码以返回JSON数组,但我遇到了一些问题。我的代码实际上变成了:

    var load_message = function(err,data){
    if (err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error creating the array');
    }
    res.writeHead(
                  200,
                    {
                        "access-control-allow-origin": origin,
                        "Content-Type": "application/json"
                    }
                  );
    res.end(JSON.stringify(data));      
  };

当我尝试呼叫我的服务器时,我没有收到任何错误但没有收到输出。 完整服务器代码(JSON版本):

var hwkey;
var app = require('http').createServer(handler),
  io = require('socket.io').listen(app),
  url = require('url'),
  fs = require('fs'),
  mysql = require('mysql'),
  connectionsArray = [],
  connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'flipper',
    database: 'oclock',
    port: 3306
  }),
  POLLING_INTERVAL = 30000,
  pollingTimer;

// If there is an error connecting to the database
connection.connect(function(err) {
  // connected! (unless `err` is set)
  if (err) {
    console.log(err);
  }
});

// creating the server ( localhost:8000 )
app.listen(8000);


function handler(req, res) {
    var origin = (req.headers.origin || "*");
    if (req.method.toUpperCase() === "OPTIONS"){
      res.writeHead(
          "204",
          "No Content",
          {
              "access-control-allow-origin": origin,
              "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
              "access-control-allow-headers": "content-type, accept",
              "access-control-max-age": 10, // Seconds.
              "content-length": 0
          }
      );
      return( res.end() );
    }

    console.log("INCOMING REQUEST: "+req.method+" "+req.url);
    req.parsed_url = url.parse(req.url, true);
    var getp = req.parsed_url.query;
    hwkey = getp.hk;
    var load_message = function(err,data){
    if (err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error creating the array');
    }
    res.writeHead(
                  200,
                    {
                        "access-control-allow-origin": origin,
                        "Content-Type": "application/json"
                    }
                  );
    res.end(JSON.stringify(data));      
  };
}


function pollingLoop(){
  // Doing the database query
  var query = connection.query('SELECT id, testo, created_by FROM flashmsgs WHERE hwk="'+hwkey+'" AND letto="0"'),
    flashmsgs = []; // this array will contain the result of our db query

  // setting the query listeners
  query
    .on('error', function(err) {
      // Handle error, and 'end' event will be emitted after this as well
      console.log(err);
      updateSockets(err);
    })
    .on('result', function(flashmsg) {
      // it fills our array looping on each user row inside the db
      flashmsgs.push(flashmsg);
    })
    .on('end', function() {
      // loop on itself only if there are sockets still connected
      if (connectionsArray.length) {

        pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);

        updateSockets({
          flashmsgs: flashmsgs
        });
      } else {

        console.log('The server timer was stopped because there are no more socket connections on the app')

      }
    });
};


// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {

  console.log('Number of connections:' + connectionsArray.length);
  // starting the loop only if at least there is one user connected
  if (!connectionsArray.length) {
    pollingLoop();
  }

  socket.on('disconnect', function() {
    var socketIndex = connectionsArray.indexOf(socket);
    console.log('socketID = %s got disconnected', socketIndex);
    if (~socketIndex) {
      connectionsArray.splice(socketIndex, 1);
    }
  });

  console.log('A new socket is connected!');
  connectionsArray.push(socket);

});

var updateSockets = function(data) {
  // adding the time of the last update
  data.time = new Date();
  console.log('Pushing new data to the clients connected ( connections amount = %s ) - %s', connectionsArray.length , data.time);
  console.log(hwkey);
  // sending new data to all the sockets connected
  connectionsArray.forEach(function(tmpSocket) {
    tmpSocket.volatile.emit('notification', data);
  });
};

console.log('Please use your browser to navigate to http://localhost:8000');

0 个答案:

没有答案