I want to append my data which is array of object format to the existing .json file so I have written code for it, but on stackoverflow I noticed so many developers suggesting before appending to existing json file first read file and then push new data to existing json file. So I followed this and made changes according to this but getting error :
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
Code written in node
newdata=[
{
UserId: '11',
UserName: 'harry',
},
{
UserId: 12,
UserName: 'David',
}
];
fs.readFile('results.json', function (err, data) {
if(data === '') {
json = JSON.parse(newdata);
json.push(newdata);
}
fs.writeFile("results.json", JSON.stringify(json));
})
This error is because you are using the .writeFile in a wrong way.
Try something like this:
fs.writeFile('results.json', JSON.stringify(newData), function(err) {
if (err) throw err;
});
A short explanation:
The ERR_INVALID_CALLBACK in the error message is the missing of the function informed in the last parameter in the example above.
fs.writeFile(<file>, <content>, <callback>)
Related
Alright, this could be really obvious, and I may not have worded the title correctly, I don't know.
I have this command that gets information on a starcraft profile, using this battlenet api. The function used to get a profiles information is
sc2.profile.profile({ id: profileId, region: profileRegion, name: profileName }, callback)
I want to be able to use the information from there for something else, and I want to pick and choose what I send and what I don't. Example:
console.log("Profile Name: " + response.displayName) /*response being the JSON, displayName being the only thing out of the JSON to be sent */
How would I go about doing that? Unfortunately I have to have a callback, and so far I haven't been able to use
var profileInfo = sc2.profile.profile({ id: profileId, region: profileRegion, name: profileName }, callback)
https://github.com/benweier/battlenet-api
callback Required. The callback function accepts two arguments error
and response.
error is only applicable when there's a connection issue to the API.
Otherwise null. body is the request response body parsed as JSON. If a
request is successful this value can still return API errors such as
'Character not found' or 'Account forbidden'. res is the response
information such as headers and statusCode
so your code would look like this
let someData;
sc2.profile.profile({ id: profileId, region: profileRegion, name: profileName },
(err, body, res) => {
// this function will be called when you receive response / error
someData = body.someData
}
);
Yo can use callback function and assign the result to a variable as following :
var profileInfo;
sc2.profile.profile({ id: profileId, region: profileRegion, name: profileName }, function(err,body,res){
profileInfo = res;
})
I'm currently using the "request" module to get data from an external page:
if i use the following code, it doesn't work:
request(SITE_URL, function (error, response, body) {
var user = new gasStation({ id: 12345, name: 'Gustavo' });
user.save();
});
But if i make the call outside the request function it works as expected:
var user = new gasStation({ id: 12345, name: 'Gustavo' });
user.save();
request(SITE_URL, function (error, response, body) {
// some stuff
});
Why is this happening?
First never ignore your error handler's. Check if error is true. Also your URL might be malformed check that. Lastly make sure the mongoose model for user is initialized. I only saw initialization outside the request.
I am attempting to update a parse user field and the function stops in the middle of it:
Parse.Cloud.define("modifyAdminStatus", function(request, response) {
var userQuery = new Parse.Query(Parse.User);
var isAdmin = request.params.adminStatus;
console.log("isAdmin:" + isAdmin);
userQuery.equalTo("username", request.params.username);
userQuery.find({ useMasterKey: true,
success: function(user) {
console.log(user.length);
console.log("Got User")
console.log(user);
user.set("isAdmin", isAdmin);
console.log("Set Status");
user.save(null, {useMasterKey: true,
success: function(user) {
response.success();
},
error: function(error) {
response.error(error.message);
}
});
},
error: function(error) {
response.error(error.message);
}
});
});
I dont get any syntax errors, when i run the code i get:
1
Got User
[ ParseUser { _objCount: 2, className: '_User', id: '2vigcitsl6' } ]
in my console. However, it seems to stop the code after i attempt to set the admin status. I have tried running it using useMasterKey but that didnt do anything so maybe I'm missing something and where the useMasterKey should go?
The answer is:
query.find({
... code here
});
Returns an array, using query.first (or selecting one object from the array) instead will get one object and allow you to set things on it.
When you're trying to save the user, parse expects two parameters. The first should be an object containing any changes, and the second should be the save options.
So in your case, simply change your save to user.save (null, {useMasterKey:true, success...})
The way you have it now would create a column on Parse.User entitled useMasterKey, if permissions allow.
SOLVED: encoding: 'utf8' needed to be set in the request.get options.
Im attempting to load a JSON file with the Request module and I'm running into an issue. Here is the code:
request.get({url: url_obj.url, json: true}, function(error, response, body) {
if (error) {
cb(error);
} else {
console.log(body.constructor);
server_obj[url_obj.server] = body;
cb(null, server_obj);
}
});
'body' is coming back as a string even though I am specifying it should be json. Very strange. If I try JSON.parse(body) its coming back 'unexpected token'. JSLint is telling me that my JSON is 100% valid.
Here is the json. Its been edited a bit (just the string bits have been changed to keep some private data away)
{
"build_info": {
"build_version": "v2.0.2.1",
"project_name": "platformsc",
"jenkins_build_url": "http://build03:8080/job/platformsc/1524/",
"git_commit_message": "the last commit.",
"git_commit_id": "c1b5dde6033977a8d183c7740ddad0f1f1589ce2",
"git_repo": "git#gitlab.blahblahblah.lan:secrets/",
"git_commit_user": "a developer",
"git_branch": "name of branch"
}
}
Taking the code examples from this site. The following boiled down code generates the following javascript error: TypeError: Object #<Promise> has no method 'read'
Code:
Azure.notification = client.getTable('notification');
var a = Azure.notification.update({
id: id,
isRead: true
}).read().done(function (result) {
console.log(result);
}, function (err) {
});
The referenced code from the link is almost identical. The only difference that I can tell is that I'm holding a reference to several different tables in the Azure object and have had no issues querying the data, only with this update. I am looking for how to determine if the update was successful or not.
todoItemTable.update({
id: idToUpdate,
text: newText
}).read().done(function (result) {
alert(JSON.stringify(result));
}, function (err) {
alert("Error: " + err);
});
After further research the following page which seems to be different uses then with the promise callback.
todoItemTable.update({ id: getTodoItemId(this), complete: isComplete })
.then(refreshTodoItems);
http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-data-html/
I'm not sure if I'm too tired from working all weekend or there is an issue with the documentation.