简体   繁体   中英

Node JS return undefined?

I am using a basic node.js introduction script, and i am passing in a argument in the command line. i want this argument to be passed back to the client after it has run. I can pass back anything that is pure text or values, but i can't pass back a variable containing the same information.

<!DOCTYPE html>
<html lang="en">
  <head>
  <meta charset="utf-8"/>
  <title>get test</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js">
  </script>
</head>
<body>
  <h1>Get Test</h1>
  <div id="test"></div>
  <script>
    $(document).ready(function() {
      $.ajax({url: 'http://localhost',dataType: "jsonp",jsonpCallback: "_testcb",cache: false,timeout: 5000,success: function(data) {
          $("#test").append(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
          alert('error ' + textStatus + " " + errorThrown);
        }
      });
    });
</script>
</body>
</html>

And this is my server code:

var http = require('http');
var arr = new Array();
http.createServer(function (req, res) {
  res.writeHead(200);

  // print process.argv
  process.argv.forEach(function(val, index, array) {
    console.log(index + ': ' + val);
    arr[index] = val;
    res.write("Size" + val);
    res.end('_testcb(\'{"Size: \' + val + \'"}\')');
  });


  console.log(arr[2]);
}).listen(80);

So my question is, how do i pass back objects/ variables/ arrays rather than static text?

If you're trying to send data to the client, you need to serialize the data into JSON in order send the values to the client.

For example, to send all of the arguments to the client, you can simply change the method to:

http.createServer(function (req, res) {
  res.writeHead(200);

  res.write("_testcb(" + JSON.stringify(process.argv) + ")");
}).listen(80);

Which will make data (on the client) an array of all the arguments to the process.

If you want to pass a different type of object, create the variable the way that you want it, and again, use JSON.stringify to convert the data to text which can then be sent. For example:

http.createServer(function (req, res) {
  res.writeHead(200);

  // create an empty object
  var data = {};

  // add a size attribute
  data["Size"] = process.argv[1];

  res.write("_testcb(" + JSON.stringify(data) + ")");
}).listen(80);

The key to all of this, is the JSON.stringify method - it allows you to convert your variables into JSON which the client then parses to be data.

You can only pass text back and forth, but you can pass text in JSON format and parse it on the client/server.

EDIT

Just in case I misinterpreted this question and you are looking to get the command line arguments that your nodejs process was started with, take a look at this thread:

How do I pass command line arguments?

The arguments are stored in process.argv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM