Execute a specialized function with imported modules and specified parameters

Within an npm project, I am looking to execute a custom function with arguments, or ideally provide it as a script in the package.json file like this:

npm run custom-function "Hello, World"
.

Currently, I have a file called src/myFunction.ts:

import * as extLib from 'libFromNodeModules'; // requiring npm to resolve this dependency

export const runFunction = function (arg: string) {
  console.log(extLib.process(arg));
};

The closest I've come to calling this function is:

{
  ...
  scripts: {
        "custom-function": "ts-node -e 'require(\"./src/myFunction.ts\").runFunction()'",
  }
  ...
}

This method does more than just executing ts-node src/myFunction.ts, however, it still doesn't allow passing arguments and might not be the correct approach. How should I properly set this up?

Answer №1

When executing the script foo.js with the argument "bar"...

"scripts": {
  "custom": "node foo.js bar"
}

To run this custom script, use the command npm run custom.

The variable process.argv contains the input from the command line...

// Inside foo.js
console.log(process.argv) // outputs ['path/node', 'path/foo.js', 'bar']

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

Is conditional CSS possible with NextJS?

While working on an animated dropdown for a navbar, I came across this interesting dilemma. In a strict React setup, you can use an inline if/else statement with onClick toggle to manage CSS animation styles. To ensure default styling (no animation) when ...

Combine large arrays

Hey, I'm encountering some issues while trying to merge large arrays in a React Native app. Specifically, I am attempting to implement infinite scroll on React Native. The issue arises when the array reaches 500+ items; every time I add more items, my ...

Tips for saving HTML data locally

Is there a way to persist my HTML element tag data even after the user closes the browser? For example: <div class="classOne" data-random="50"> If I use jQuery to change the data attribute like this: $(".classOne").attr("data-random","40") How ca ...

React useState Error: Exceeded maximum re-renders. React enforces a limit on the number of renders to avoid getting stuck in an endless loop

Can someone help me troubleshoot the 'Too many re-renders' error I'm encountering? I've implemented the try, catch method along with React hooks like useState and setState. My goal is to fetch data from an API and display it on a ...

AJAX (Vanilla JavaScript): Sending Image through HTTP Request

I am a beginner with ajax and prefer not to use frameworks. I attempted to use PHP to determine if a file is set and display either true or false, but it didn't work as expected. I'm unsure of where I went wrong. Below is my HTML and JS code: & ...

Refreshing the browser does not load the Angular2 component and instead shows a 404 error

During my exploration of Angular 2, I developed a basic restaurant management application. Now, I am delving into more advanced techniques such as creating an app bundle, minification, and optimizing the application. The authentication component in my app ...

What is the best way to display HTML code using Vue syntax that is retrieved from an Axios GET request

I am currently working on a project that involves a Symfony 5 and Vue 3 application. In this setup, a Symfony controller creates a form and provides its HTML through a JSON response. The code snippet below shows how the form HTML is returned as a string: i ...

"Troubleshooting Typecscript and Angular: Dealing with mismatched argument

How can I resolve this Angular error: (response: HttpResponse<User>) => { which results in the following error message: Argument of type '(response: HttpResponse<User>) => void' is not assignable to parameter of type '(val ...

How come I can't capture discord.js promise rejections within event callbacks?

As I delve into creating a discord bot, I encountered an interesting problem. To simplify things, here is a snippet that encapsulates the issue at hand: const Discord = require('discord.js'); const client = new Discord.Client(); client.on(&apo ...

Error: Express is undefined and does not have a property called 'use'

I'm encountering a problem with my express server specifically when I utilize the 'app.use' command. Within my task-routes.js file, the following code is present: import express from 'express'; const router = express.Router(); ...

Creating a custom pipe that converts seconds to hours and minutes retrieved from an API can be achieved by implementing a transformation function

Can someone please provide guidance on creating a custom pipe in Angular 8 that converts seconds to hours and minutes? Thank you. <div class="col-2" *ngFor="let movie of moviesList"> <div class="movie"> {{ movie.attributes.title }} ...

Tag editor assessing the input's width for SO

I've been working on a tag editor similar to Stack Overflow's and it's coming along nicely. The only issue I'm facing is calculating the width of the textbox after a tag has been selected by the user. For each tag added, I try to adjus ...

Why do I keep encountering the error "global is not defined" when using Angular with amazon-cognito-identity-js?

To start, run these commands in the command line: ng new sandbox cd .\sandbox\ ng serve Now, navigate to http://localhost:4200/. The application should be up and running. npm install --save amazon-cognito-identity-js In the file \src&bso ...

What alternatives are there to angular scope functions?

I find angular scope functions challenging to work with due to their lack of a clear contract. They extract parameters from the scope and store results back into the scope, rather than explicitly defining function parameters and returning a result. Conside ...

Merging a VUE project and a .NET framework project to unleash their full potential

Currently, I am working on a project that involves using VUE for the client side and .net framework for the server side. However, these two components are hosted as separate projects, requiring me to open different ports during development. I am aware tha ...

The jQuery included does not function properly in production mode and results in an error stating that it is not a function

After placing the jquery.placeholder.js file in the assets/javascripts folder, I successfully applied the function in my coffeescript file and it worked perfectly. $(document).ready -> $('input, textarea').placeholder(); However, when swit ...

What is the technique for performing asynchronous querying of multiple SQL databases?

Currently, I am in the process of developing a web application using nestjs and typeorm. I have been contemplating the functionality of the following code: const r1 = await this.connection.query(sqlA) const r2 = await this.connection query(sqlB) Does th ...

What is causing my reusable component to malfunction when used in conjunction with the "setInterval" function?

I have created a custom <Loader /> component in which I can pass the text it is rendering and the speed as props. The code for the component is shown below: class Loader extends Component { constructor(props) { super(props); this.state = { ...

Node.js allows for keeping pipe and sockets open even after streaming an HTTP response

My current challenge involves streaming data from an HTTP response to a cloud storage provider within an internal service. const response = await request<Readable>({ headers: httpOpts?.headers, data: httpOpts?.data, url, method, responseTyp ...

Error found in the HTML tag data when viewing the page source for an issue

I am displaying some data from my express to ejs in HTML tag format. It appears correctly on the ejs template page and the web page. However, when I check the page source, the HTML tags are encoded and displayed as unescaped characters. Is there a solution ...