Query an API with NodeJS or a file

Query an API with NodeJS or a file

NodeJS is a very common platform for the development of server-side applications, web-based interfaces. Naturally, this makes it convenient to use NodeJS to call another interface or to download a remote file over HTTP/S. By using modules such as axios or node-fetch, you can easily send HTTP requests to external APIs and process their responses. With the built-in fs module (File System), you can read, write, modify, and delete files locally.

Download a file with NodeJS

The code begins by importing the required NodeJS modules: https for HTTPS requests, fs for file operations, and path for working with file paths. Then, an asynchronous function named downloadFile is defined, which takes a URL and a destination path as parameters.

Within the downloadFile function, a stream is created to save the downloaded file at the destination. With https.get, a GET request is made to the provided URL. Upon response, it checks if the status code is 200, which indicates a successful download. If not, the partially written file is deleted, and the Promise is rejected with an error message

const https = require('https');
const fs = require('fs');
const path = require('path');

async function downloadFile(url, dest) {
    return new Promise((resolve, reject) => {
        const file = fs.createWriteStream(dest);

        https.get(url, (response) => {
            if (response.statusCode !== 200) {
                fs.unlink(dest, () =>
                    reject(`Failed to download file: Status Code ${response.statusCode}`));
                return;
            }

            response.pipe(file);
            file.on('finish', () => file.close(resolve));

        }).on('error', (err) => {
            fs.unlink(dest, () => reject(err)); // Delete the file async on error
        });
    });
}


const url = 'https://cdn.renick.io/media/exchange/ttf/tesla-noise.m4a';
const dest = path.join(__dirname, 'downloaded_file.jpg');

downloadFile(url, dest)
    .then(() => console.log('File downloaded successfully'))
    .catch(err => console.error('Error downloading file:', err));

Make an HTTP request with NodeJS

The following code uses the https module to retrieve an API. The http module is available for unencrypted connections. An asynchronous function named get is defined, which takes a URL as an argument. This function returns a Promise, which is typical for asynchronous operations in JavaScript. Within the function, https.get is used to send a GET request to the provided URL.

During the processing of the response from the HTTP request, the status code is checked first. If the status code is not 200, which means successful with content, the Promise is rejected with an error message, and the execution of the function is terminated

const https = require('https');

async function get(url) {
    return new Promise((resolve, reject) => {
        https.get(url, (response) => {
            if (response.statusCode !== 200) {
                reject(`Request failed with status code ${response.statusCode}`);
                return;
            }

            let data = '';
            response.on('data', (chunk) => data += chunk);
            response.on('end', () => resolve(data));

        }).on('error', (error) => {
            reject(error);
        });
    });
}


const url = 'https://www.renick.io/sitemap.xml';

get(url)
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));