How to save JSON file with Node.js

4

I want to make a website to test some things. The site is running on my home server made with Wamp. I was told I could make a small database using JSON files. I have a JSON file in the site folder that contains the following:

[
        { 
            "titulo":"Filme A",
            "titulo original":"Movie A",
            "duracao":"120 min",
            "genero":"Genero 1",
            "Atores":"Nome 1, Nome 2",
            "Rate":"1",
            "Visto":"sim"
        },
        {
            "titulo":"Filme B",
            "titulo original":"Movie B",
            "duracao":"160 min",
            "genero":"Genero 2",
            "Atores":"Nome 1, Nome 2",
            "Rate":"2",
             "Visto":"sim"
        },
        {
            "titulo":"Filme C",
            "titulo original":"Movie C",
            "duracao":"140 min",
            "genero":"Genero 3",
            "Atores":"Nome 1, Nome 2",
            "Rate":"",
             "Visto":"nao"
        }
]

With your help I was able to list the properties of these JSON array objects.

Now I'm trying to save a new object inside this JSON array through information that the user places when the questions are asked and for this I need a scripting on the server side, I chose the Node .js for being a bit more familiar with JavaScript. I have little knowledge and almost none of Node.js. But even so I would like any help from you so I try to learn something. I have read on the internet about the node.js and JSON but I still have not understood how to save the JSON on the server using the node. Any explanation will be a lot of help.

See the JSFiddle

    
asked by anonymous 31.01.2014 / 01:57

2 answers

4

The most indicated one, that was mentioned by Joel is yes to actually use Mongo, but if you are interested in using a file manipulation API in Node.JS, you can use Filesystem API , see an example below

var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
}); 

Or as the example below, it could be the use of Node.JS with connection to MongoDB

var MongoClient = require('mongodb').MongoClient,
Grid = mongo.Grid;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
    if(err) return console.dir(err);

    var grid = new Grid(db, 'fs');
    var buffer = new Buffer("Hello world");
    grid.put(buffer, {metadata:{category:'text'}, content_type: 'text'}, function(err, fileInfo) {
        if(!err) {
             console.log("Finished writing file to Mongo");
        }
    });
});
    
31.01.2014 / 03:32
2

I recommend using a JSON MongoDB database in Node.js.

link

I recommend learning and reading more about how to use MongoDB:

link

link

    
31.01.2014 / 03:23