Execute the JS file to retrieve the initial port available within the npm script

Within my package.json, I have the following script:

    "dev": "webpack-dev-server --config webpack.dev.js --progress --port ${getPort()}",

I've also installed a package called get-port, which allows me to set a default port and obtain an alternative if the default is in use.

I'm interested in utilizing this dependency to retrieve the port for the script mentioned above (where getPort() is indicated). How can I execute JavaScript inline and capture the returned value from a function?

Answer №1

Avoid using random ports, especially if you are connecting with other services such as the Facebook API. Instead, consider implementing a gulp script to manage the process on your specific port.

Have you thought about setting it to automatically assign a port in webpack? Check out more information here.


If you prefer a customized approach, one option could be to create a gulp script that uses 'get-port' to find an available port and then launches the ng serve command accordingly. Make sure to have gulp and get-port installed before running this code snippet:

const getPort = require('get-port');
const exec = require('child_process').exec;
var gulp = require('gulp');

async function serveMe() {
    gulp.task('serve', function (cb) {
      exec("ng serve --port " + await getPort(), function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
      });
    })
}

exports.serveMe = serveMe;

Update your package.json file:

"start": "gulp serveMe",

Answer №2

Typically, the suggestion would be to utilize the CLI version of this tool, allowing for easy integration into shell scripts. However, as it appears you've faced challenges installing get-port-CLI, here is an alternative approach:

You can execute code inline using node -e <script code>, specifically with

require('get-port')().then(console.log)
:

webpack-dev-server --config webpack.dev.js --progress --port $(node -e 'require(\"get-port\")().then(console.log)')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing Statements in a Specific Order with Express and Sqlite3

I am having an issue creating a table and inserting an item into it using the node command. Despite my efforts to reorganize my script, the item is being inserted before the table is created. Interestingly, manually inputting the commands in sqlite3 works ...

What is causing this connection code to have such a lengthy runtime of nearly 5 seconds?

const DatabaseClient = require('mongodb').MongoClient; let performanceCount = 0, interval = setInterval(function(){ performanceCount++; }, 0); const url = 'mongodb://localhost:27017/test'; DatabaseClient.connect(url, ...

Guide to activating jpeg compatibility in node-canvas on x64 windows using MSVC10 compiler?

To display jpeg images on a Node.js server, I decided to use the canvas npm module. I followed the installation instructions provided at https://github.com/Automattic/node-canvas/wiki/Installation---Windows. I have C:\libjpeg-turbo\ as mentioned ...

Converting RGBA to Hex Color Code with Javascript: A Step-by-Step Guide

I attempted to change the rgba color representation to hexadecimal, but I encountered difficulty in converting the opacity value while successfully converting the remaining colors. Here is the snippet of my code: var colorcode = "rgba(0, 0, 0, 0.74)"; ...

Executing a JavaScript function using document.write()

When I try to click on the SWF part1 links within the document.write() function in order to call the openswf function, nothing happens. Here is my code: <html> <a href="#" onclick="Popup();">show popup</a> <script> functio ...

Adding a JavaScript object into the $http service

Struggling to correctly insert an object in this format: $scope.newObj = {1: "N/A", 2: "KO", 3: "OK", 4: "OK", 5: "OK", 15: "N/A", 19: "OK"} An attempt was made using the following loop: var objt = $scope.newObject; console.log($scope.newObject[0] ...

Reviewing for the presence of "Undefined" in the conditional statement within Transpiled Javascript code for

While perusing through some transpiled Angular code, I came across this snippet: var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { I'm puzzled by the usage of undefined in this context. Can an ...

Copy the click function to a contenteditable <div> with spellcheck feature

When using a contenteditable <div> in Chrome, the native spell check feature will only work if the user manually clicks into the <div>. But what if you want to add a contenteditable <div> dynamically? Is there a way to trigger the spell c ...

The use of url.resolve() function with greater than two arguments

Currently, I'm utilizing the url.resolve() function to combine components of a URL from a configuration file in this manner: var uri = url.resolve(config.baseUrl, this.orgId, this.appId, type) However, it appears that using more than two arguments d ...

Is it possible for npm 5 to make --no-save the default option?

Is there a way to configure npm 5 to retain the old behavior of not saving the installed dependency without having to use a switch? For example, I'm accustomed to running npm install <package> without it affecting package.json, and I prefer to ...

Bring in the Stencil JS library from a separate Stencil JS library

Within my collection of Stencil JS web components, I have two distinct libraries - library-a and library-b. These are not complete applications, but rather separate npm packages containing various components. I am interested in incorporating certain compo ...

Issue: missing proper invocation of `next` after an `await` in a `catch`

I had a simple route that was functioning well until I refactored it using catch. Suddenly, it stopped working and threw an UnhandledPromiseRejectionWarning: router.get('/', async (req, res, next) => { const allEmployees = await employees.fi ...

When utilizing the JavaScript createElement() method to create elements on keydown, it will not be compatible with jQuery's draggable() method

I'm currently developing a drag and drop feature for a project, allowing users to add items to a work area and then position them by dragging. I'm facing an issue where I want to create multiple instances of the same element using a key code, but ...

Encountering an issue while setting up the ContextAPI in nextJS, where properties of undefined Provider cannot be read

I'm encountering difficulties in implementing ContextAPI with a nextjs application. The error message I keep receiving is: TypeError: Cannot read properties of undefined (reading 'Provider') This is my approach to creating the context: impo ...

Guide on incorporating custom items alongside default items in the Context Menu of Handsontable

I attempted to utilize handsontable and am interested in incorporating custom additions to the context menu. While there are numerous tutorials on how to implement custom menus, they often overlook the default items. In an effort to address this issue, I ...

Fundamentals of object property in jQuery and Javascript

Currently working on creating a new property named startPosition and setting the top property to equal the button's current top value in CSS. Below is the jQuery code snippet: var morphObject = { button: $('button.morphButton'), c ...

Can we prevent a component from being mounted every time it is rendered by its parent component?

Is it possible to render the Child component within the Father component without mounting it and resetting its states when the Father component is rendered? I attempted to use the useMemo hook to render the Child component, but it still mounts the compone ...

Struggle with registering fonts in Canvas using JavaScript

I've been struggling to add a custom font to my canvas for hosting the bot. Even though I'm not encountering any errors, the font fails to display on the host. Below is the code snippet: const { AttachmentBuilder } = require('discord.js&apos ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

Creating a compact Swiper slider: reducing image size without sacrificing full window coverage!

Utilizing Swiper to craft a slider that occupies the entire window, with a slight margin for a bar-- no issues there. (https://i.sstatic.net/qcGBA.jpg) However, the image I placed in for the slide () appears to be excessively enlarged. Is there a way to ...