2
\$\begingroup\$

I have this view that populates an unordered list from values in a JSON file, which I am doing in Node.

Is there a better way to do this, or a more 'node-like' way? Can I load the JSON file without an Ajax call?

<!DOCTYPE html>
<html>
<head>
    <title>4&middot;pli -- news</title>
    <link rel='stylesheet' href='/stylesheets/style.css'/>
    <script src="/javascripts/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script src="/javascripts/date.format.js" type="text/javascript"></script>
    <link href='http://fonts.googleapis.com/css?family=Didact+Gothic' rel='stylesheet' type='text/css'>
</head>
<body>
<% include shared/nav.ejs %>
<div class="wrapper">
    <ul class='news'>
       <script type="text/javascript">
           $.ajax({
               url: 'data/news.json',
               async: false,
               dataType: 'json',
               success: function (response) {
                   var items = [];
                   $.each(response.news,function(i,item){
                       items.push('<li><ul><li class="title">'+ item.title +'</li><li>' + dateFormat(item.created_at,"fullDate") + '</li><li><p>'+ item.content +'</p></li></ul></li>');
                   });
                   $('.news').append(items.join(''));
               }
           });
       </script>
    </ul>

</div>
<% include /shared/footer.ejs %>
</body>
</html>
\$\endgroup\$
  • 2
    \$\begingroup\$ async: false --- baaaad \$\endgroup\$ – John Dvorak May 16 '13 at 20:37
  • \$\begingroup\$ @JanDvorak elaborate futher please. \$\endgroup\$ – Antarr Byrd May 16 '13 at 20:38
  • 4
    \$\begingroup\$ Normally javascript runs from the browser's UI thread. This means that while the browser is waiting for the AJAX response, user interaction is disabled. \$\endgroup\$ – John Dvorak May 16 '13 at 20:46
  • \$\begingroup\$ @JanDvorak Thanks I will try and remember that. \$\endgroup\$ – Antarr Byrd May 16 '13 at 20:48
4
\$\begingroup\$

What you're looking for is JSON.parse. It's not in the Node docs, because it's "lower" than that: Every modern javascript runtime has it (see MDN).

Here's a simple function to read a file, parse it as JSON, and send it to a callback (all in Node)

function readJSONFile(filename, callback) {
  require("fs").readFile(filename, function (err, data) {
    if(err) {
      callback(err);
      return;
    }
    try {
      callback(null, JSON.parse(data));
    } catch(exception) {
      callback(exception);
    }
  });
}

In keeping with Node conventions (and just mirroring readFile itself), you pass it a callback with this signature: function(err, json). E.g.

readJSONFile("path/to/file.json", function (err, json) {
  if(err) { throw err; }
  console.log(json);
});

You can make a none-async one if you prefer, but Node's nature is async.

\$\endgroup\$
2
\$\begingroup\$

your question is not so clear.

if you use express (expressjs.com) it is pretty easy:

/**
* Module dependencies.
*/

var express = require('express')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 80);
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);

var o = require('./news.json');

app.get('/news', function(req, res){
     res.json(o);
});

http.createServer(app).listen(app.get('port'), function(){
     console.log('Express server listening on port ' + app.get('port'));
});

you can create a custon route:

app.get('/news', function(req, res){
     res.json([{title: 'test', content: 'test desc'}, {title: 'test2', content: 'test2 desc'}])
}

or even from a db: (using mongoose.js)

app.get('/news', function(req, res){
     news.find().exec(function(err, result) {
         res.json(err || result);
     }); 
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.