Please some help with this, im new with nodejs and this is a common issue and and im tried the examples in anothers posts here. I have problem when in the last function.
Im trying:
- Check if a data.json exists and create it with a some data with async.waterfall
function IfDataDontExistsCreate(callback)
{
async.waterfall([ //If data dont exists
function IfExistDataFile(callback) {
fs.exists(path, function(exists){
if(!exists)
{
try {
const firstDataFile = {"readedPosts":{"id": []}};
const json = JSON.stringify(firstDataFile, null, 2);
callback(null, json);
} catch (error) {
callback(error);
}
}
}
)},
function CreateDataFile(json ,callback) {
fs.writeFile(path, json, function (err) {
if(err) callback(err);
})
}
], function (err, callback) {
if(err) throw err;
});
callback(null, callback);
}
- Read data.json, get data, add some info and save data.json with async.waterfall
function AppendtoDataFile(info, callback)
{
async.waterfall([
function ReadGetData(callback) {
fs.readFile(path, (err, data) => {
if(err) throw err;
let datajson = JSON.parse(data.toString());
datajson.readedPosts.id.push(info.toString()); //Add info
callback(err, datajson)
})
},
function WriteDataFile(data, callback) {
const writeData = fs.writeFile(path, JSON.stringify(data, null, 2), function (err) {
if(err) throw err;
callback(err);
})
}
], function(err, callback)
{
if(err) throw err;
});
callback(null, callback);
}
- Join the functions with async.series
function AddPostID(postID, callback)
{
async.series({
one: function (callback) {
IfDataDontExistsCreate(function () {
callback(null, "DataFile Created");
});
},
two: function (callback) {
AppendtoDataFile(postID, function () {
callback(null, "PostID added to Datafile");
});
}
}),
function (err, results) {
if(error) throw err;
console.log(results);
}
}
await.