Is there a way to obtain the tasklist result of exec() from child_process and convert it to JSON format?

When I use the tasklist command with child_process, the stdout returns processes in Unicode string format that is not easily queryable.

Here is the code snippet:

var exec = require('child_process').exec;
...

exec('tasklist', function(err, stdout, stderr) {
    ...
});

An example part of the stdout output:

    \r\nImage Name                     PID Session Name        Session#    Mem Usage\r\n========================= ======== ================ =========== ============\r\nSystem Idle Process              0 Services                   0          8 K\r\nSystem                           4 Services                   0      3,900 K\r\nRegistry                       148 Services                   0     57,232 K\r\nsmss.exe                       636 Services                   0        444 K\r\ncsrss.exe                      820 Services                   0      3,604 K\r\nwininit.exe                    716 Services                   0      2,824 K\r\nservices.exe                     8 Services                   0      9,180 K\r\nlsass.exe...
            

Is there a way to retrieve the stdout output in JSON format?

I have tried various methods to convert from Unicode to JSON but have not found a simple solution yet.

Answer №1

Split the given string into lines, and then split each line into an array of values. Utilize this array to create a JSON object.

For example:

const exec = require('child_process').exec;

exec('tasklist', function(err, stdout, stderr) {
    const lines = stdout.split("\n");
    const json = [];

    for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();
        if (line === "") continue;
        const values = line.split(/\s+/);
        json.push({
            "imageName": values[0],
            "pid": values[1],
            "sessionName": values[2],
            "sessionNumber": values[3],
            "memUsage": values[4]
        });
    }

    console.log(json);
});

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

What is the most effective method for displaying a child modal within a map?

Project link: Check out my project here! I have two key files in my project - App.js and PageFive.js. In App.js, there is an array defined as follows: state = { boxes: [ { cbIndex: "cb1", name: "Bob" }, { cbI ...

Prevent sticky div from overlapping with footer

I currently have a social link menu that is fixed to the left side of my page, structured like this: <footer id="colophon"></footer> <div> <nav> <ul id="social"> <li>Link1</li> ...

JavaScript - Two tables shown in parallel

Beginner coder seeking assistance! I am currently working on an application with two user input fields placed adjacent to each other. Clicking parse buttons next to these fields generates two separate tables. However, I need these tables to be displayed si ...

Array in Javascript reset to null after its second iteration

''' const users = [] const addUser = ({ id, username, room }) => { // Clean the data username = username.trim().toLowerCase() room = room.trim().toLowerCase() // Validate the data if (!username || !room) { r ...

The setCountry function fails to properly change the country value

My goal is to establish a default country selection in checkbox options, I have three choices: United States, United Kingdom, and Rest of the world; Here's the constant called AVAILABLE_COUNTRIES which contains the iso codes for the mentioned countrie ...

Unable to render HTML through Jquery ajax functionality

success: function(json) { for (var i = 0; i < json.length; i++) { var response = json[i]; $('#rv-container').html('<p>' + response.name + '</p>' + '<span>' + response ...

When utilizing the built-in filter in Angular 2 ag-grid, the Clear Filter button efficiently removes any text from the filter box without needing to refresh the

When using ag-Grid's default filter feature, I noticed that the clear filter button only clears the text box and does not automatically refresh the column, even when the 'clearButton' and 'applyButton' parameters are set to true. T ...

Loading indicator displayed at the top of a div using JavaScript/jQuery

My current challenge involves implementing a progress bar, similar to the pace.js progress bar. The issue arises when the browser is refreshed, as the pace.js progress bar loads on top of the body instead of within a specified div. It is important that the ...

There was an issue with deserializing NewtonSoft Json due to a problem converting a string to a decimal value: /Date(1490721584000-0500

I am working on an ASP.Net MVC project where I'm using the NewtonSoft json deserializer to consume a json web service that sends dates in the /Date()/ format. The json I am receiving looks like this (showing just the first array element): [ { " ...

Adding information into the database using Anypoint Studio

I want to extract and store the data from this json file in a database using Anypoint Studio: To achieve this, I utilized an http connector with the link to the JSON file, followed by a json-to-object transformer and a database connector. In my database, ...

Trouble with the navigation of the JavaScript image gallery: next and previous buttons are not

Is it possible to have multiple galleries on a single page with captions? I've been trying to incorporate this JavaScript code, but struggling to make the next/previous links function for both galleries. Since I'm new to JavaScript, any advice or ...

NodeJS instructs open(html) to execute first before any other code is executed

I am evaluating whether nodeJS is a suitable solution for a project I am working on during my internship. To summarize: I need the basicNode.js file to wait until the open('./basic.html') command has completely opened the browser and loaded its c ...

Altering the appearance of an input field upon submission

https://jsfiddle.net/3vz45os8/7/ I'm working on a JSFiddle where I am trying to change the background color of input text based on whether the word is typed correctly or incorrectly. Currently, it's not functioning as expected and there are no e ...

Tips on retaining label names for input boxes

Check out this Plunker example. I am trying to figure out how to keep labels on top of textboxes in this Plunker. Can anyone help me with that? <a class="btn btn-success btn-xs" data-nodrag ng-click="toggle(this)"><span class="glyphicon" ng-clas ...

Update the choices in a dropdown menu dynamically using MVC Razor

In my HomeController, I have written a code snippet that is intended to retrieve the latest 6 rows from a database. private List<SelectListItem> GetOriginalIDs(string thisPWS) { List<SelectListItem> list = new List<SelectListItem>(); ...

Stop the Enter key from functioning as a mouse click

Whenever an element is focused on and a mouse click action can be triggered, I've observed that the Enter key functions as if you're clicking the mouse left button. This behavior is causing conflicts in other parts of my code, so I need to find a ...

How can we determine the total character count of a file that has been loaded into a textarea

I have a textarea where I can count the number of characters as I type. function calculateCharacters(obj){ document.getElementById('numberCount').innerHTML = obj.value.length; } <textarea name="textField" id="my_textarea" class="text_edit ...

Executing a command in the terminal for each line of a JSON document

I have a JSON file containing tweets that I gathered using Tweepy. In order to perform sentiment analysis on each tweet, I am trying to utilize the API provided by www.text-processing.com. Below, you can see my current (flawed) code. fname = 'python. ...

retrieve data from JSON file

function retrieveDataFromProfiles(){ const fs = require('fs') fs.readFile('src/data/profileInfo.json', function(error, data){ if(error){ alert(error); } var profileData = JSON.parse(data); //retrieves the JSON data of ...

NVDA fails to announce the "dialog" when a Modal is launched

When testing this simple modal example, I noticed that although the role is set to dialog and focus is correctly received on the dialog container when it opens, NVDA fails to announce the word 'dialog' at the beginning. This issue has been report ...