I have this node code
//change the variable to what the database file is
var dataFile = "data.json";
//set to port you want server hosted on
var port = 8000;
//End Of settings
var fs = require('fs');
var http = require('http'),
url = require('url');
if (fs.exists(require('path').resolve(__dirname, dataFile))) {
data = JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
dataFile),
'utf8'));
console.log("data setup!");
} else {
fs.writeFile(dataFile, "{}", function (err) {console.log("database file has been created!");});
console.log('Please restart ndb.js to get the database online.');
console.log('you can quit with ctrl + c');
}
function writeSaveData() {
fs.writeFile(dataFile, JSON.stringify(data), function (err) {
if (err) throw err;
console.log('Updated the file: ' + dataFile + " with new data");
data = JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
dataFile),
'utf8'));
console.log("Completed re-sync of data");
});
}
http.createServer(function (req, res) {
query = url.parse(req.url,true).query;
if(query.act) {
if(query.act === 'store') {
if(query.name && query.val){
eval('data.' + query.name + ' = "' + query.val + '"');
writeSaveData();
res.end("success!");
} else {
res.end("{'error':'Error wrong parameters'}");
}
}
if(query.act === 'read') {
if(query.name) {
res.end(eval('data.' + query.name));
} else {
res.end("{'error':'Error wrong parameters'}");
}
}
} else {
res.end("{'error':'Error wrong parameters'}");
}
//res.end(JSON.stringify(query));
}).listen(port);
console.log("Server running at http://localhost:" + port + '/');
what happens is that when i run this code it thinks that the if statement executes false and ends up resetting my file with data! I have no idea what is happening. I do have the data.json file with basic json in it so i don't know what is wrong!
Aucun commentaire:
Enregistrer un commentaire