问题描述:

I work on a site that manage football league, with utilizing angularjs & nodejs without any database...

I treat with teamsInfo.json like this:

var express = require('express'),

http = require('http');

var fs = require('fs');

var teamsInfo = require('./data/teamsInfo.json');

var app = express()

.use(express.bodyParser())

.use(express.static('public'));

app.get('/teamsInfo', function (req, res) {

res.json(teamsInfo);

});

app.post('/teamsInfo', function (req, res) {

teamsInfo.push(req.body);

fs.writeFile('./data/teamsInfo.json', JSON.stringify(teamsInfo));

res.json(req.body);

});

app.post('/teamsInfo/:id', function (req, res) {

//something

});

It works correctly but thats not a point, my problem is when you want to store and show week result to user.

Our result data store like this: result1.json - result2.json - result3.json and ...

If i wanna treat with this json's like teamsInfo.json I should right many get and post functions to handle request and response. And the point is all of them do the same thing, because the format of result json's are same.

my question is:

  1. how can I create json file when user click on nextWeekResult function? (I evalute name by a counter then create it physically in my system)

  2. how can I write just one get and post functions that handle all result.json files?

Thanks.

网友答案:

I'm not super clear about what your asking, but to dynamically load/save files you can use the id provided to build dynamic filenames to target. An example to dynamically get a file based on id, if you're letting your end user specify the id to use:

app.get('/teamsInfo/:id', function(req, res) { 
  // dynamically build file to load based on id
  var filename = util.format('teamsInfo%s', req.params.id);
  var teamInfox = require(util.format('./data/%s.json, filename));
  res.json(teamsInfox);
});
相关阅读:
Top