Wednesday 17 May 2017

How do I perform Regex Match in Node JS?

var http = require('http');
var fs = require('fs');
var extfs = require('extfs');
var exec = require('child_process').execSync;
var url = require('url');
const PORT=8282;

function handleRequest(request, response){

  var regex = fs.readFileSync('./output.txt', 'utf8');
  var res = regex.match(/<.*class='.*(post-title).*>\n.*</g);

  response.end(res);
}


var server = http.createServer(handleRequest);
server.listen(PORT, function(){
  console.log("Server listening on: http://localhost:%s", PORT);
});

The above is my Node JS web server which upon running, will start up a temporary web server listening at port 8282.

I've tested my regex in https://regex101.com/ to make sure it's able to match properly.

My problem is when I make a GET request, my web server will crash and the error I get is First argument must be a string or Buffer I understand this is due to the asynchronous nature of Node JS and response.end(res) got run first before the lines above have completed.

I'm not sure how to fix this. Any suggestion would be greatly appreciated.



via Kelvin Low Ee Hahn

No comments:

Post a Comment