JavaScript runs in web browsers and Node.js, environments that don't provide direct access to the filesystem or networking. However, JavaScript needs to fetch external data like JSON APIs, images, files etc. The urllib library provides this capability.
The
const urllib = require('urllib');
// Fetch JSON data
urllib.request('https://api.example.com/data', function(err, data) {
if (err) {
throw err;
}
// data is a string containing the response body
});
The
Handling Responses
The response
const obj = JSON.parse(data);
Errors are returned in the
urllib.request(url, function(err, data) {
if (err) {
// handle error
}
});
Advanced Usage
Additional options like timeout, headers, POST data etc. can be passed to customize the request:
urllib.request(url, {
dataType: 'json', // auto parse JSON response
data: { key: 'value' } // POST body
headers: { 'User-Agent': 'myapp' },
timeout: 3000, // 3s timeout
});
The