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·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>
2 Answers 2
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.
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);
});
}
async: false
--- baaaad \$\endgroup\$