I am using writeFileSync function to write a file locally, the file does get written, however, the callback function is never called.
I did some googling, some other post are having the issue that it's either 1) passing the content went wrong or 2) having two write function at the same time.
My problem is that there are some other places in my code that is using the writeFileSync, but they are on different routes (not sure if this is the right terminology, localhost:port#/differentroutes <- something like this). I am testing only on my own route so those write functions shouldn't even be called.
Here is my code:
if(!fs.existsSync(dir)){
fs.mkdirSync(dir)
}
//content is just a string var I swear it's just a string
fs.writeFileSync('./pages/SubmissionProcess.html',content,function(err){
if(err){
throw err
}else {
console.log("YES")
}
})
I never see this "YES" nor error in my console even tho the file is already written....
Write file sync doesn't take a callback :D
Take a look at the documentation :
https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options
The parameters are (path, data, options)
If you want to check if the file actually wrote, you can read file sync after writing it or check the last time the file was updated. Otherwise, you should try using the async approach.
All of the synchronous methods throw rather than passing an error to a callback.
try {
fs.writeFileSync('./pages/SubmissionProcess.html', content);
console.log('YES');
} catch (e) {
console.error(e);
}
Related
I have a js file called example.js which has a line as follows:
gridOptions.api.setRowData(createRowData());
Then there's another file data.js which has the createRowData() function that should return ROW_DATA. It is as follows:
function createRowData() {
jQuery.getJSON('/file.txt',function(ROW_DATA){
return ROW_DATA;
});
}
But, whenever this createRowData() function is called from example.js file, it does not go inside the jQuery block and simply comes to the last curly bracket. Can anyone please tell me what is going wrong here??
I believe that you're not getting the value because getJSON is asynchronous as others have said. createRowData is retrieving the value at a later time rather than when it's called.
Here is one way to get the data with promises. I commented what's going on below:
function createRowData() {
//return a new promise
return new Promise(function(resolve, reject){
jQuery.getJSON('/file.txt',function(ROW_DATA){
//on reject, send an error
if (ROW_DATA === null) reject("Error fetching data");
//on resolve, send the row data
return resolve(ROW_DATA);
});
});
}
//use then to describe what happens after the ajax request is done
gridOptions.api.setRowData(createRowData()).then(function(rowdata){
return rowdata; //log data or error
})
Edit: to do a synchronous ajax request, you may be able to do something like this, referring to this SO question.
function createRowData() {
$.ajax({
url: "/file.txt'",
async: false,
success: function(rowdata){
return rowdata
}
})
}
To read some data to a variable like you mentioned, nodejs may help because it can handle reading input/output, and probably to a variable as well.:
You get JSON from the file, pass the result to the callback function, and then return it. Return it where??
As I said, your anonymous function is a callback one.
Program says: When you are done reading from the file, call this function, OK?.
While you do that, I am doing something else.
And that is what it does. The program, would go on, until the file is read, when your callback anonymous function would be called.
You can do sth like this.
createRowData(gridOptions.api);
// add code here if you want this code to execute even before you get the response
function createRowData(api) {
jQuery.getJSON('/file.txt',function(ROW_DATA,api){
api.setRowData(ROW_DATA);
//Whatever else you want to do. In case you want this to be done only
//after the values have been read
});
}
If you want to wait, for the file to be read, just, dont do anything after the function, but put it inside the callback function.
I know that there's a completion handler for .set and .update, but I was wondering if there was something like that for .forEach.
For example, something like this:
firebase.database().ref().child('kid').orderByChild('date').on('value', function(snapshot) {
snapshot.forEach(function(kid) {
}, function(error) { //This is where the error is thrown
}
});
If this isn't possible, is there a workaround? I just need a function to call once the .forEach method is done running.
P.S. My function is actually stated in another file, but I just call it normally.
No, it is a synchronous javascript function. Simply add a line after the function.
Reworded:
A common pattern is to pass callback functions, such as with Mongoose's save (just for example and simplified - no error handling):
someMethod(req:Request, res:Response){
document.save( function(err){ res.status(200).send({message: 'all good'})});
}
I'd like to externalize the callback. You can do this this way:
var respond = function(err:any, res:Response){
res.status(200).send({message: 'all good'});
}
someMethod(req:Request, res:Response){
document.save( function(err){ respond(err, res)});
}
...but ideally I'd like to do this by just passing a function like respond without having to create a call back function to enclose respond. I wanted to know if this is possible. Since the anonymous function has access to res, I thought there might be some way to gain access to res in a function defined externally. It appears there is not a way to do this so I'll live with wrapping it.
My original question was trying to isolate the specific issue I was interested in - which is to gain access to the caller's variables implicitly. Doesn't seem like that is possible. Fair enough.
Original Question:
I'd like to externalize a bit of code I use frequently and I'm having trouble understanding closure in the context of a Typescript method. Take a look:
var test = function(){
console.log("Testing external: "+JSON.stringify(this.req.body));
}
class Handler {
static post(req: Request, res: Response){
(function(){
console.log("TESTING anon: "+JSON.stringify(req.body));
}) ();
test();
}
}
Besides the fact that this does nothing useful, in this bit of code, the inline anonymous function has access to the req object, but the test() function does not. this in test is undefined. Removing this to match the inline function doesn't help.
I believe if I were to bind on this for the call I'd just end up with a reference to the Handler class when I really want to bind on the post method.
My motivation for doing this is that I want to make a function that can be passed as a callback to a bunch of different request handlers. When I write the functions inline it all works, but when I externalize it I can't get a closure over the variables in the enclosing method. I've read "You Don't Know JS: this & Object Prototypes", and in pure Javascript I can manage to make these sorts of things work but I'm obviously doing something wrong here (it may not be Typescript related, maybe I'm just messing it up).
So bottomline - is there a way I can externalize the handler and get access to the method variables as if I were writing it inline? I could just create an inline anonymous function as the callback that calls the external function with all the variables I need, but I want to really understand what is happening here.
This is not an answer, but will hopefully give me enough feedback to give you one because its not at all clear what you're actually trying to accomplish here and whether or not you actually understand what the terms mean is an open question since you use them correctly one minute and sketchily the next.
var test = function(){
console.log("Testing external: " + JSON.stringify(this.req.body));
}
In strict mode this will throw an error, in sloppy it will try to access the req property of the global object which is not likely what you want.
(function(){
console.log("TESTING anon: "+JSON.stringify(req.body));
}) ();
The IFFE wrapper is completely unnecessary, it literally adds nothing to the party. So why include it?
static post(req: Request, res: Response){
console.log("TESTING anon: "+JSON.stringify(req.body));
test(); // is this the spot where you are 'in-lining?'
}
What I think you want is this:
var test = function(reqBody) {
console.log("Testing external: " + JSON.stringify(reqBody));
};
class Handler {
static post(req: Request, res: Response) {
test(req.body);
}
}
I'm new to Javascript and trying to figure out how to properly write this.
$.get("https://localhost:8090/", function(response) {
console.log(response) #this works as expected
$.get("https://localhost:8090"+response), function() {
console.log('response') #nothing is printed
};
})
The response from $.get("https://localhost:8090/" is /oauth2callback. On my server (flask), I have logging enabled and I can see that the function inside the route is running properly.
The server code looks something like this:
#app.route('/oauth2callback')
def oauth2callback()
if 'code' not in flask.request.args:
logging.warning('code not in args')
auth_uri = flow.step1_get_authorize_url()
logging.warning(auth_uri)
return auth_uri
I can see in the log file that auth_uri is accurate.
However, I do not see console.log('response') being printed in my console. I assume this is due to my poor Javascript skills and not writing the callback correctly?
How should I structure this?
Thanks!
You have an extra ) by mistake
$.get("https://localhost:8090"+response), function() {
// ....................................^ remove this paren
}); // <--- and add it here
Relatively new to Javascript/Jquery!
tl;dr When I call a function (defined in an external library that I include), my success AND failure callback functions simply do not fire. Given my code below, is this an issue with my javascript or theirs?
I am using an external API along with it's Javascript library, which I include like so:
app/views/layouts/application.html.haml :
= javascript_include_tag 'application'
<script type="text/javascript" src="http://parcelstream.com/api/DmpApi.aspx?map=Bing&services=Utility&host=parcelstream.com/&v=4"></script>
My javascript, which is run on page load:
app/assets/javascripts/mine.js :
function GetByGeometry(point) {
function successCallback(json) {
console.log("success callback called");
// real code here, cut for brevity
}
function errorCallback(error) {
console.log("error callback called");
// real code here, cut for brevity
}
var url = "getByGeometry.aspx?returnGeoType=1&dataSource=SS.Base.Parcels/Parcels&Geo=" + point;
console.log("this is my query URL: " + url);
Dmp.Env.Connections["SS"].getJson(url, successCallback, errorCallback);
}
I am getting no feedback whatsoever. Neither successCallback nor errorCallback are ever fired off, and I am not getting an error either. What am I missing? Is this an error on my end, or is there something wrong with their .getJson() function?
Any insight would be greatly appreciated!
I don't have any clue about the Dmp.Env.Connections["SS"] object, so I cannot tell if that is working or not.
First thing to do is to look into the Network tab (under Developer Tools in Chrome) and check if an Ajax call is fired. This is will tell a lot - if a response is received from the server, if your payload is correct etc. I would start there, and then check for the API definition of Dmp.Env.Connections["SS"] and see if my arguments are correct.
Hope that helps.