1

Having this function in express that writes a JSON file on a folder

var savingtheJson=function(path, jsonObject, callback){
  jsonfile.writeFile(file2, jsonO, callback);
}

I will like to know how can I access/read this file from the browser once is saved.

If I do this:

savingtheJson('/json/myfile.json', jsonObj, function(){
            console.log("done it!");
        });

When I go to the browser and I type:

http://localhost:8080/json/myfile.json

Of course I get an error from express "Cannot Get ...." cause I think is trying to resolve it like an specific request

How can I store this file into the static folder declared for this goal (app.use(express.static(__dirname + '/public'))?

How can I access this file once is saved?

niutech
  • 28,923
  • 15
  • 96
  • 106
Frnnd Sgz
  • 236
  • 1
  • 4
  • 19
  • The static service directory is in '/public', just like you mentioned. But IMO you should instead provide a new endpoint in your web service for retrieving the file. – E_net4 Oct 13 '15 at 21:44
  • You mean to create and endpoint on the app that reads the file like using this kind os function on this example? [reading json file](http://stackoverflow.com/questions/12703098/how-to-get-a-json-file-in-express-js-and-display-in-view) – Frnnd Sgz Oct 13 '15 at 21:47
  • 1
    You would definitely not read the file like that in a server application. I meant to create a new route (e.g. `/json/:myfile`) and asynchronously read the file there on GET. – E_net4 Oct 13 '15 at 21:49
  • you can load a json file to a variable by simply calling require! – Ali Oct 13 '15 at 22:31

1 Answers1

13

First you need to define which folder is going to be exposed as public, so that you can save your json file inside there.

You can use the built-in middleware express.static for this purpose.

Below in the example I have created a endpoint called /users?name=wilson&age=32 which receives query data in order grab user's information as name and age for then you can save it as file named person.json.

So after you consume the above endpoint mentioned, you will be able to consume your file with something like http://localhost:4040/person.json successfully.

var express = require('express');
var app = express();
var port = 4040;
var fs = require('fs');

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

app.get('/users', function(req, res) {
  var name = req.query.name;
  var age = req.query.age;

  var person = {
    name: name,
    age: age
  };

  savePersonToPublicFolder(person, function(err) {
    if (err) {
      res.status(404).send('User not saved');
      return;
    }

    res.send('User saved');
  });
});

function savePersonToPublicFolder(person, callback) {
  fs.writeFile('./public/person.json', JSON.stringify(person), callback);
}

app.listen(port, function() {
  console.log('server up and running at port: %s', port);
});
Wilson
  • 9,006
  • 3
  • 42
  • 46