npm | Replace package.json latest with actual latest version numbers | Run NPM in javscript with in-memory file-system | Search

This code checks if a local npm server is running by sending a request to a specified host and port and verifying the response status code.

Run example

npm run import -- "Check if there is a local-npm server running on Brian's machine"

Check if there is a local-npm server running on Brian's machine

var http = require('http');
var os = require('os');
function checkLocalNPM(host) {
    var HOST = host || os.hostname() || 'localhost';
    return http.get(
        'http://' + HOST + ':5080',
        (r) => r.statusCode === 200)
        .on('error', (e) => false);
};
module.exports = checkLocalNPM;

What the code could have been:

// Import required modules
const http = require('http');
const os = require('os');

/**
 * Checks if the local npm instance is running at the specified host.
 * If no host is provided, it defaults to the local hostname or 'localhost'.
 *
 * @param {string} [host=os.hostname()] - The host to check.
 * @returns {Promise<boolean>} - A promise resolving to true if the instance is running, false otherwise.
 */
function checkLocalNPM(host) {
  // Determine the host to check
  const HOST = host || os.hostname() || 'localhost';

  // Create an HTTP GET request
  return new Promise((resolve, reject) => {
    const request = http.get(`http://${HOST}:5080`, (response) => {
      // Resolve the promise with true if the status code is 200
      resolve(response.statusCode === 200);
    });

    // Reject the promise with the error if an error occurs
    request.on('error', (error) => {
      reject(error);
    });
  });
}

// Export the function
module.exports = checkLocalNPM;

This code defines a function checkLocalNPM that checks if a local npm server is running.

Here's a breakdown:

  1. Imports:

  2. checkLocalNPM Function:

In essence, this code provides a simple way to determine if a local npm server is running on the specified host and port.