node_request Function
Syntax
Arguments
- nodeService
Name of the node service to run.
- pData
Pointer to parameters to pass to the node service.
- flagRestartNode
.t. or .f. value. Default .f.
Flag indicating whether or not the node server should be restarted when node_request is called. .t. restarts the node server. Restarting the node server can be useful for debugging purposes. flagRestartNode should be set to .f. in a production environment.
- flagShowCommandWindow
.t. or .f. value. Default .f.
Show the command window for the node service handler (allows developer to see feedback using console.log() in the handler).
- flagAllowDebug
.t. or .f. value. Default .f.
Enable node debugger (requires that the node debugger be launched).
Description
Calls a node service from Xbasic. Returns a JSON string.
The node_request function calls a node service for a web project. The web project must include a 'node_services' folder with the named node service. If the service is not present in the project, you will receive an error from node.
Below is an example call - it assumes a node service called 'eval' that reads javascript to execute from a 'content' property, then returns the result.
dim req as p dim req.content as c = "1+1" ? node_request("eval",req) = {"_id":"d18fa451-5c15-4cbf-8085-92fe24890e4d","error":"command eval was not recognized for command d18fa451-5c15-4cbf-8085-92fe24890e4d","result":null}
Add a node_services to the projects 'node' subfolder - save a file called 'eval.js' that has the following contents:
exports.handler = function(packet,response,sendResponse) { var e; var attachments = null; try { response.result = eval(packet.content); if( Buffer.isBuffer(response.result) ) { attachments = [{ name : 'data' , type : 'binary' , data : response.result }]; response.result = 'binary data in attachment'; } } catch( e ) { response.error = e.message; } sendResponse(response,attachments); };
The node service handler consumes a 'packet' that contains the parameters for the command. In this case, the parameter required is called "content", and gets evaluated, data is returned in a result parameter.
With 'node_services/eval.js' defined, now our example should work, notice that the result of evaluation is in a field called 'result', notice also that 'error' is blank.
dim req as p dim req.content as c = "1+1" ? node_request("eval",req) = {"_id":"d21a4938-d8bd-455f-9e82-e70bcc675316","error":"","result":2}
An example of a valid request with a handled error would be to pass a javascript expression that is invalid.
dim req as p dim req.content as c = "1+" ? node_request("eval",req) = {"_id":"4bee3d41-7816-4f0c-8b3f-ca853fa2ef0c","error":"Unexpected end of input","result":null}
Automatic Node Restart
If you edit a Node Service, Alpha Anywhere will automatically set flagRestartNode to .T. in Live and Working Preview. If Node is not restart, any changes made to a Node Service will not be detected.