Killing the command prompt in Typescript: A step-by-step guide

Is there a way to completely close the cmd where the typescript file is running but unable to do so?

How can this be achieved?

console.log('This ts file must be terminate itself');

let asdef = process.pid;
let asdeff = process.ppid;

const {exec} = require('child_process')

// Terminating a PID and its child processes
exec(`Taskkill /PID ${asdef} /T`, (err, stdout, stderr) => {
    if (err) {
    throw err
    }

    console.log('stdout', stdout)
    console.log('stderr', err)
})

Error Messages:

Error: Command failed: Taskkill /PID 7440 /T
ERROR: The process with PID 16320 (child process of PID 16876) could not be terminated.
Reason: The process cannot terminate itself.
ERROR: The process with PID 16876 (child process of PID 7440) could not be terminated.
Reason: One or more child processes of this process were still running.
ERROR: The process with PID 7440 (child process of PID 10880) could not be terminated.
Reason: One or more child processes of this process were still running.

Answer №1

You have two options to achieve this:

If you want to terminate all open cmd instances.

  console.log("Closing all cmd instances..")
  exec('taskkill /IM cmd.exe')

Terminate the cmd instance where the script is running. Assign a unique value to a CMD environment variable, set it as the title of the cmd, find the cmd using this title, and terminate it by its PID.

console.log("Searching current cmd...")
// set unique env variable
exec('set uniqueTitle=%time%%random%');
// set title cmd with env variable
exec('title=%uniqueTitle%')
exec('for /f "tokens=2 delims= " %A in (\'tasklist -v ^| findstr /i "%uniqueTitle%"\') do (taskkill /PID %A)', (err: string, stdout: string) => {
    if (err) {
        throw err
    }

    console.log('stdout', stdout)
    console.log('stderr', err)
})

Complete code:

console.log('This ts file must be terminate itself');

let asdef = process.pid;
let asdeff = process.ppid;

const { exec } = require('child_process')

//console.log("Closing all cmd opened..")
//exec('taskkill /IM cmd.exe')

 console.log("Searching current cmd...")
// set unique env variable
exec('set uniqueTitle=%time%%random%');
// set title cmd with env variable
exec('title=%uniqueTitle%')
exec('for /f "tokens=2 delims= " %A in (\'tasklist -v ^| findstr /i "%uniqueTitle%"\') do (taskkill /PID %A)', (err: string, stdout: string) => {
    if (err) {
        throw err
    }

    console.log('stdout', stdout)
    console.log('stderr', err)
})

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

Spartacus has the capability to extend or override the PageType enum within the cms.model framework

I am facing a dilemma similar to the Spartacus situation. In brief, I am required to modify the PageType enum in cms.model by either overriding or extending it. The current enum consists of four values (content, product, category, catalog) and I must incl ...

Using React.js and TypeScript to leverage a single component for both <input /> and <textarea /> elements

After developing an <Input /> component with helper components for improved usability and code reduction within the main component, I encountered an issue while attempting to create a <textarea /> HTML element. The problem arises from using Rea ...

Leverage a TypeScript property descriptor to substitute the accessors without compromising on composability

Is there a way to create a TypeScript property descriptor that can override accessors and still be easily composed with other functionality? ...

Is there a way to remove trigger characters in vscode api completion function?

I am developing a vscode extension that requires custom completion for json files. I would like to know if it is possible to hide the trigger character when using autocompletions. Let me explain further : Imagine the trigger character is '.' In ...

Showing container element only if certain condition is met but display the children in Angular 2+

I am looking to create a grid-style view for a list of Angular components, where I can display up to 4 components in each row. The question that comes close to what I need is the following: Angular 2 NgIf, dont render container element on condition but sh ...

What is the best way to incorporate an exported TypeScript class into my JavaScript file?

One of my JavaScript files is responsible for uploading a file to Microsoft Dynamics CRM. This particular JavaScript file makes use of RequireJS to reference another JavaScript file. The referenced JavaScript file, in turn, was compiled from multiple Typ ...

The error `TypeError: Unable to access properties of an undefined value (reading 'authService')` occurred

I'm attempting to check if a user is already stored in local storage before fetching it from the database: async getQuestion(id: string): Promise<Question> { let res: Question await this.db.collection("questions").doc(i ...

In just a single line of code, you can iterate through a Record object and retrieve an array of DOM elements

I am working with an object type MyType = 'name' | 'base' | 'six'; obj: MyType = { 'name': {key: 'm1'}, 'base': {key: 'm2'}, 'six': {key: 'm3'}, } My goal is ...

Accept only the keys specifically assigned to an object

Trying to develop a TypeScript class where it is initialized with an object and contains a method that only accepts keys from that object. Here's the code: class MyClass { properties = {}; constructor(properties) { this.properties = propertie ...

I am in need of a customized 'container' template that will display MyComponent based on a specific condition known as 'externalCondition'. MyComponent includes the usage of a Form and formValidation functionalities

container.html <div ngIf="externalCondition"> <!--Initially this is false. Later became true --!> <my-component #MyComponentElem > </my-component> <button [disabled]= "!myComponentElemRef.myDetailsF ...

Challenges with implementing Typescript in Next.js and the getStaticProps function

Having trouble with the implementation of getStaticProps where the result can be null or some data. The typings in getStaticProps are causing issues, even after trying conditional props. Any suggestions? type ProductType = { props: | { ...

How can time duration be accurately represented in TypeScript?

As I work on designing an interface for my personal project, I am in need of adding a field that represents the length of time taken to complete a task. What data type and format should I use in TypeScript to express this? Below is the interface I have cr ...

Failure of React to connect event handlers

LATEST UPDATE: After removing the output entry from my webpack configuration, the React event listeners are now functioning correctly. Currently, I am diving into the world of hand-rolling webpack configurations for a React/TypeScript application for the ...

Optimal method for retrieving data from a JSON object using the object's ID with a map

Can you teach me how to locate a json object in JavaScript? Here is a sample Json: { "Employees" : [ { "userId":"rirani", "jobTitleName":"Developer", "preferredFullName":"Romin Irani", "employeeCode":"E1", "region":"CA", "phoneNumber":"408-1234567", " ...

Limit function parameters to only accept values with matching keys

I am relatively new to using TypeScript and am currently working on a project that involves handling various shapes of data from different sources. My goal is to pass this data to different aggregator classes, with one aggregator class corresponding to eac ...

Exploring the return type of the `within` function in TypeScript Library

I have helpers set up for my React tests using the testing library: const getSomething = (name: string, container: Screen | any = screen) { return container.getByRole('someRole', { name: name }) } The container can be either the default screen ...

Angular 2+ encountering an internal server error (500) while executing an http.post request

Here is my service function: public postDetails(Details): Observable<any> { let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: cpHeaders }); return this.htt ...

There is a WARNING occurring at line 493 in the file coreui-angular.js located in the node_modules folder. The warning states that the export 'ɵɵdefineInjectable' was not found in the '@angular/core' module

I encountered a warning message while running the ng serve command, causing the web page to display nothing. Our project utilizes the Core Ui Pro Admin Template. Here is the list of warning messages: WARNING in ./node_modules/@coreui/angular/fesm5/coreu ...

Remove the ability to select from the dropped list item

Here is the HTML and Javascript code I used to enable drag and drop functionality for list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop list in Green Area: </h4> <ul class="unstyle"> & ...

Ways to resolve the issue with the Argument of type 'Date[]' not matching the parameter type '(prevState: undefined) in React

I've encountered an issue while trying to construct my project. The error message reads as follows: Argument of type 'Date[]' is not assignable to parameter of type '(prevState: undefined) Here's the excerpt of the code in questio ...