Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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>
share|improve this question
2  
async: false --- baaaad – Jan Dvorak May 16 '13 at 20:37
    
@JanDvorak elaborate futher please. – Antarr Byrd May 16 '13 at 20:38
4  
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. – Jan Dvorak May 16 '13 at 20:46
    
@JanDvorak Thanks I will try and remember that. – Antarr Byrd May 16 '13 at 20:48
up vote 4 down vote accepted

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.

share|improve this answer

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);
     }); 
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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