From the course: Node.js: Web Servers, Tests, and Deployment

Making a request with the GET method - Node.js Tutorial

From the course: Node.js: Web Servers, Tests, and Deployment

Making a request with the GET method

- [Instructor] In the previous video, we used the HTTPS module to make a request to Wikipedia. Now, let's refactor that code a little bit and use the https.get method. And we're also going to refactor this to use a stream. Now, the first thing we need to do is we need a url and our url is going to be the same from before. So we'll say wikipedia.org/wiki/Cher. Now, once we've done that, we can delete our options object. We're also going to make some adjustments to the request function. So instead of using request, we'll use get. And we are going to pass in instead of options, we'll say url. Because we're saying that we want to make this get request, we don't have to define all of those other options, which is kind of nice. We will use the same callback function here but we're going to use slightly different code inside of this. So let's go ahead and get rid of everything that's here. And we want to create a variable called download. And we're going to set this equal to fs.createWriteStream. And we'll pass in the name of the file that we want to write to. So we'll say cher.html. Then we'll console.log Response started. And then we'll use response.pipe download. So we want to pipe that data into our file finally. We need to call response.on and what we'll do here is we'll console.log a message for ourselves. We'll say response finished. Okay, perfect. So now let's try to run this again. We're going to make sure that we're navigated to the right folder. I feel like I'm not. So we'll get there. There we go. Node index said started and then finished. And then we have our HTML page over here once again. So with this code, the results are the same but the code to make this download happen is a little cleaner and more efficient using the get method.

Contents