2

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.

2
  • Why don't you use a parser instead? Commented May 17, 2017 at 16:50
  • I've not used parser before. Could you please explain how it works? I working example would be great. Commented May 17, 2017 at 16:51

1 Answer 1

2

No, it has nothing to do with asynchronous execution, the lines in your code are executed sequentially.

Your issue is that the match() function returns an array of strings, i.e. neither a string nor Buffer

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for pointing out the error. In this case should I continue to use match() or there's a better way for me to do regex in Node JS?
@KelvinLowEeHahn I so no reason to use something else. Depends on exactly what you're trying to accomplish though of course. If you need something more complex than just simple matching you should look at the RegExp exec() function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.