I am looking for a way of getting the process memory of any process running.
I am doing a web application. I have a server (through Nodejs), my file app.js, and an agent sending information to app.js through the server.
I would like to find a way to get the process memory of any process (in order to then sending this information to the agent) ?
Do you have any idea how I can do this ? I have searched on google but I haven't found my answer :/
Thank you
PS : I need a windows compatible solution :)
Windows
For windows, use tasklist instead of ps
In the example below, i use the ps unix program, so it's not windows compatible.
Here, the %MEM is the 4st element of each finalProcess iterations.
On Windows the %MEM is the 5th element.
var myFunction = function(processList) {
// here, your code
};
var parseProcess = function(err, process, stderr) {
var process = (process.split("\n")),
finalProcess = [];
// 1st line is a tab descriptor
// if Windows, i should start to 2
for (var i = 1; i < process.length; i++) {
finalProcess.push(cleanArray(process[i].split(" ")));
}
console.log(finalProcess);
// callback to another function
myFunction(finalProcess);
};
var getProcessList = function() {
var exec = require('child_process').exec;
exec('ps aux', parseProcess.bind(this));
}
// thx http://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript
function cleanArray(actual){
var newArray = new Array();
for(var i = 0; i<actual.length; i++){
if (actual[i]){
newArray.push(actual[i]);
}
}
return newArray;
}
getProcessList();
Related
I have two Office.js applications:
Prototype written in pure javascript
React application
I can successfully call an end-point in the pure javascript application that downloads an MSWord document. This file is whole, complete and un-corrupted.
However, virtually identical code in the React application, calling the same end-point, downloading the same MSWord document returns a slightly larger data length (42523 vs 40554), The data begins identically, then changes as follows:
Working snippet of the document data
80,75,3,4,20,0,6,0,8,0,0,0,33,0,70,117,100,65533,1,0,0,32,8,0,0,19,0,8,2,91,67,111,110,116,101,110,116,95,84,121,...
Corrupted snippet of the document data
80,75,3,4,20,0,6,0,8,0,0,0,33,0,70,117,100,63462,63411,1,0,0,32,8,0,0,19,0,8,2,91,67,111,110,116,101,110,116,95,...
In my (working) pure javascript application the code looks like this:
downloadPath = "https://myserver.com/seal-ws/v5/downloads/6bb4dfd7e0a528dc68f2069f9d5da5a732692f49";
var xhr = new XMLHttpRequest;
xhr.open("GET", downloadPath);
xhr.addEventListener("load", function () {
var ret = [];
var len = this.responseText.length;
let trace = '';
for (let i = 0; i < len; i += 1) {
trace += this.responseText.charCodeAt(i) + ",";
}
console.log(trace);
console.log(len);
}, false);
xhr.setRequestHeader("X-Session-Token", XSessionToken);
xhr.overrideMimeType("octet-stream; charset=x-user-defined;");
xhr.send(null);
In the React application the code that returns the corrupt file looks like this:
const downloadPath = "https://myserver.com/seal-ws/v5/downloads/6bb4dfd7e0a528dc68f2069f9d5da5a732692f49";
const xhr = new XMLHttpRequest;
xhr.open("GET", downloadPath);
xhr.addEventListener("load", function () {
const ret = [];
const len = this.responseText.length;
let trace = '';
for (let i = 0; i < len; i += 1) {
trace = `${trace}${this.responseText.charCodeAt(i)},`
}
console.log(trace);
console.log(len);
}, false);
xhr.setRequestHeader("X-Session-Token", XSessionToken);
xhr.overrideMimeType("octet-stream; charset=x-user-defined;");
xhr.send(null);
I've used fiddlr to inspect the outgoing requests from both applications, and both look well formed and identically to one another. I don't understand why the response is being corrupted in the React application with what looks like near identical code?
It's not a browser difference, as I've tested with IE on both applications. The only thing I can think of is that the prototype is using a different version of the javascript file for the XMLHttpRequest object.
Pure Javascript App:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\JavaScript\References\domWeb.js
React app:
C:\Users\\AppData\Local\Programs\Microsoft VS Code\resources\app\extensions\node_modules\typescript\lib\lib.dom.d.ts
Any ideas?
The above is a simplified version of what I'm trying to achieve in-order to illustrate the slight corruption in the data between the two approaches. Ultimately I'm trying to achieve a MSWord document download followed by an open new instance command as the following code describes. As detailed above, the following code workings in the prototype pure javascript application, but has this slight corruption in the React app. The resulting document opens correctly from pure javascript and fails to open the corrupted version from the React app. I'm sure it's nothing to do with React as a framework, but I struggling to understand what differences there could be that would cause the resulting data to be mis-decoded in this way:
const downloadPath = "https://myserver.com/seal-ws/v5/downloads/6bb4dfd7e0a528dc68f2069f9d5da5a732692f49";
const xhr = new XMLHttpRequest;
xhr.open("GET", downloadPath);
/* eslint-disable no-bitwise */
xhr.addEventListener("load", function () {
const ret = [];
const len = this.responseText.length;
console.log('len');
console.log(len);
let trace = '';
for (let i = 0; i < len; i += 1) {
trace = `${trace}${this.responseText.charCodeAt(i)},`
}
console.log(trace);
let byte;
for (let i = 0; i < len; i += 1) {
byte = (this.responseText.charCodeAt(i) & 0xFF) >>> 0;
ret.push(String.fromCharCode(byte));
}
let data = ret.join('');
data = btoa(data);
console.log(data);
Word.run(context => {
const myNewDoc = context.application.createDocument(data);
context.load(myNewDoc);
return context.sync().then(() => {
context.sync();
myNewDoc.open();
});
});
}, false);
xhr.setRequestHeader("X-Session-Token", XSessionToken);
xhr.overrideMimeType("octet-stream; charset=x-user-defined;");
xhr.send(null);
Since two snippets that generate different outputs have nothing to do with React, try to just copy paste it to have the identical snippet in both projects.
I guess, the problem is that you do this:
trace = `${trace}${this.responseText.charCodeAt(i)},`
Which duplicates trace value instead of just accumulating new characters' codes on each iteration.
The main function file main.js has:
var nLastPingTime = 0,
nLastPingNumber = 0;
module.exports = {
compareData: function(nPingTime, nLastPingNumber){
nLastPingTime = nPingTime;
nLastPingNumber = nLastPingNumber;
}
};
Now two other files dataGenOne.js and dataGenTwo.js look something like this:
const mainDataHolder = require('./main.js');
//Gets data from some API's here
mainDataHolder.compareData(nPingTime, nLastPingNumber);
Then to start we run:
node dataGenOne.js
and
node dataGenTwo.js
The problem is that the main.js file doesn't share nLastPingTime and nLastPingNumber mutually between both sets of data.
For example when looking at nLastPingNumber, its the number from dataGenOne.js specifically and not from dataGenTwo.js at all (or vise versa).
I believe this is because they are running on two separate threads.
Is there anyway to achieve what I'm trying to do? The alternative could be to connect database or write to a file but if possible I would rather not do that.
To achieve what you are attempting to do, have two node processes communicate, you are going to have create process, lets call it spawn, that spawns both of the processes (let's call them p1 & p2) and then handles communication between p1 & p2.
So spawn would be a very simple process that would just wire the events for p1 & p2 and then forward those events to the other process. I don't have a working example of this but if you take a look here you should be able to piece that together pretty quickly.
Adam H pointed me in the right direct. The correct way to do this is in fact child_processes.
Below are the code changes:
The main function file main.js now has:
var cp = require('child_process');
var childDataOne = cp.fork('./dataGenOne.js', [process.argv[2]], { silent: true });
var childDataTwo = cp.fork('./dataGenTwo.js', [process.argv[3]], { silent: true });
childDataOne.stdout.on('data', function(data) {
console.log('parent: ' + data);
compareData(data);
//Here is where the output goes
});
childDataTwo.stdout.on('data', function(data) {
console.log('parent: ' + data);
compareData(data);
//Here is where the output goes
});
Now two other files dataGenOne.js and dataGenTwo.js changed to something like this:
process.stdin.resume();
var passingString = nPingTime + "," + nLastPingNumber;
process.stdout.write(passingString);
To start running we only have to do:
node main.js param1 param2
Instead of running dataGenOne.js and dataGenTwo.js individually.
This correctly allows the child processes to pass data back to the parent process. main.js is listening with stdout.on and the two dataGen child processes are passing the data with stdout.write.
So to avoid the complexity of storing these variables somewhere, merge the processes, but reorganize your code to make it easier to navigate.
main.js (the compare function?) - remove the variables from the top but make sure the compare function returns the latest ping values along with the comparison data i.e.
return {
data,
lastPingTime,
lastPingNumber
}
move the api stuff into separate files so you can do this
var dataSetOne = require('./dataOne');
var dataSetTwo = require('./dataTwo');
var datasets = [dataSetOne, DataSetTwo];
// initialize the values
var lastPingTime = 0;
var lastPingNumber = 0;
// loop through the datasets
for (var i = 0, len = datasets.length; i < len; i++) {
let currentDataSet = datasets[i];
const results = comparePrices(lastPingTime, lastPingumber, aAsks, aBids);
// update the ping info here
lastPingTime = results.lastPingTime;
lastPingNumber = results.lastPingNumber;
}
And if you have a lot of datasets, make an 'index.js' file that does all those requires and just returns the datasets array.
Hope that helps!
I am working on Protractor for testing the Angular JS application. I have written a code to read the data from excel sheet.My scenario is like I have a end to end flow that should execute.The code will take the URL,UserName and Password from the excel sheet and will execute the entire flow. Than again it will iterate the other value. But its not going into the loop.
My code is:
var Excel = require('exceljs');
var XLSX = require('xlsx');
var os = require('os');
var TEMP_DIR = os.tmpdir();
var wrkbook = new Excel.Workbook();
//---------------------Duration as Days------------------------------------------
describe('Open the clinicare website by logging into the site', function () {
it('IP Medication Simple flows for Patient Keerthi for Days,Weeks and Months', function () {
console.log("hello6");
browser.driver.manage().window().maximize();
var wb = XLSX.readFile('E:\\LAM WAH EE_Testing Enviornment\\IP_Medication_Flow\\Patients_Entry.xlsx');
var ws = wb.Sheets.Sheet1;
var json = XLSX.utils.sheet_to_json(wb.Sheets.Sheet1);
console.log("json", json);
//var json = XLSX.utils.sheet_to_json(wb.Sheets.Sheet1);
//console.log("json", json);
for(var a = 0; a < json.length ; a++){
console.log("Test_URL", json[a].Test_URL);
console.log("User_Name", json[a].User_Name);
console.log("Password", json[a].Password);
browser.get(json[a].Test_URL);
console.log("hello10");
//Perform Login:UserName
element(by.model('accessCode')).sendKeys(json[a].User_Name);
browser.sleep(6000);
// browser.driver.sleep(6000);
//Perform Login:Password
element(by.model('password')).sendKeys(json[a].Password);
browser.sleep(6000);
//Hospital Name
element(by.cssContainingText('option', 'HLWE')).click();
browser.sleep(6000);
//Perform Login:LoginButton
element(by.css('.btn.btn-primary.pull-right')).click();
browser.sleep(6000);
//Clicking on Admitted Tab
element(by.xpath("//span[contains(text(),' Admitted(25)')]")).click();
browser.sleep(6000);
// browser.driver.sleep(6000);
//Clicking on First Admitted Patient
element(by.cssContainingText('span.clearfloat', '35690')).element(by.xpath('//*[#id="searchPatientImgAdmittedF"]')).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 600000;
// browser.sleep(600);
//Clicking anywhere to proceed
element(by.xpath('/html/body/div[3]/div[1]/div[16]/div[1]/div/table[4]/tbody/tr[2]/td/div/div/div[3]/table/tbody/tr[1]/td[3]')).click();
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
browser.sleep(800);
Anyone's help is appreciated. Thanks in advance.
Alright initially confused with the 'exceljs' node module. It is not used in your test. I think the major problem here is that the file does not exist.
readFile and ENOENT
The first thing of the readFile is an alias for readFileSync which calls readSync which calls (probably) read_binary which offloads to node's fs.readFileSync. More than likely the fs.readFileSync is throwing the ENOENT because the path does not exist.
Looking at your path, you might need a backslash before your spaces.
var wb = XLSX.readFile('E:\\LAM\ WAH\ EE_Testing Enviornment\\IP_Medication_Flow\\Patients_Entry.xlsx');
It could be a good practice to get the file path with path.resolve prior to calling the read file method.
var path = require('path');
var patientEntryFilePath = path.resolve('E:\\LAM\ WAH\ EE_Testing Enviornment\\IP_Medication_Flow\\Patients_Entry.xlsx');
console.log(patientEntryFilePath);
var wb = XLSX.readFile(patientEntryFilePath);
Additional comments and thoughts about the original code snippet
Some additional comments about the code snippet from the original question. Maybe considerations for future cleanup.
Think about using a beforeAll or beforeEach for setting your browser driver window size and reading in a file. Reading in the file once is potentially a time and resource saver.
describe('Open the clinicare website by logging into the site', function () {
var json = null;
beforeAll(() => {
browser.driver.manage().window().maximize();
var wb = XLSX.readFile('E:\\LAM\ WAH\ EE_Testing Enviornment\\IP_Medication_Flow\\Patients_Entry.xlsx');
var ws = wb.Sheets.Sheet1;
json = XLSX.utils.sheet_to_json(wb.Sheets.Sheet1);
});
it('IP Medication Simple flows for Patient Keerthi for Days,Weeks and Months', function () {
console.log("json", json);
...
Looking at your test that it is a login and it appears to have the same flow, you really only need to test this once. The for loop is acceptable since the json file is resolved and each line is executed in the control flow that Protractor uses.
Avoid using xpath. It is better to find elements by css or id or partial path. In the developer adds an additional div in the list of div's will break your test, making your test more fragile and require more upkeep.
This because Protractor API execute Async, but the For loop execute Sync. Get detail explain from here, which is same issue as yours.
To fix your issue, we can use javascript closure.
for(var a = 0; a < json.length ; a++) {
(function(a){
console.log("Test_URL", json[a].Test_URL);
console.log("User_Name", json[a].User_Name);
console.log("Password", json[a].Password);
browser.get(json[a].Test_URL);
console.log("hello10");
//Perform Login:UserName
element(by.model('accessCode')).sendKeys(json[a].User_Name);
browser.sleep(6000);
// browser.driver.sleep(6000);
//Perform Login:Password
element(by.model('password')).sendKeys(json[a].Password);
browser.sleep(6000);
...
})(a)
}
If I execute a certain shell command in node js, the output is on the console. Is there a way I can save it in a variable so it can be POST to Sqlite database.
const shell = require('shelljs');
shell.exec('arp -a');
In this scenario, I want to store the IP address of a specific MAC/Physical address into the database. How can this be done?
Any help would be much appreciated. Thank you
You need to get the output of the command you're passing to exec. To do that, just call stdout, like this:
const shell = require('shelljs');
const stdout = shell.exec('arp -a').stdout;
Then just parse that output to get your ipaddress:
const entries = stdout.split('\r\n');
// entries sample
[ '',
'Interface: 10.17.60.53 --- 0xd',
' Internet Address Physical Address Type',
' 10.11.10.52 6c-4b-90-1d-97-b8 dynamic ',
' 10.10.11.254 xx-yy-53-2e-98-44 dynamic ']
Then you can filter your wanted address with some more manipulation.
EDIT:
To get the ip address, you could do:
let ipAddr = null;
for (let i = 0; i < entries.length; i++) {
if (entries[i].indexOf('6c-4b-90-1d-97-b8') > -1) {
ipAddr = entries[i].match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/)[0];
break;
}
}
console.log(ipAddr); // '10.11.10.52'
I'm merely copy pasting from the docs. You should research more.
You need to add a listener to stdout
var child = exec('arp -a', {async:true});
child.stdout.on('data', function(data) {
/* ... do something with data ... */
});
Or adding the callback directly when calling exec
exec('some_long_running_process', function(code, stdout, stderr) {
console.log('Exit code:', code);
console.log('Program output:', stdout);
console.log('Program stderr:', stderr);
});
You can access the result of the command run using shell.exec with the .output property. Try the code below.
var shell = require('shelljs');
var result = shell.exec('arp -a').output;
If you don't want the result in the console, you can specify the silent option.
var result = shell.exec('arp -a', {silent: true}).output;
Now, you can use regular expressions to extract ip and mac address from the result.
I am getting the result of the command like below:
? (xxx.xxx.xxx.xxx) at xx:xx:xx:xx:xx:xx [ether] on eth0
? (yyy.yyy.yyy.yyy) at yy:yy:yy:yy:yy:yy [ether] on eth0
You can use the following code to extract ip and mac.
var res = result.split("\n").map(function(item){
return item.match(/\((\d+\.\d+\.\d+\.\d+)\) at (..:..:..:..:..:..)/);
});
console.log(res[0][1]); //IP of first interface
console.log(res[0][2]); //MAC of first interface
console.log(res[1][1]); //IP of second interface
console.log(res[1][2]); //MAC of second interface
NOTE
I was not able to find the .output property in the documentation but trying the shell.exec function in the node console revealed it.
The .stdout property or the exec function mentioned in other answers doesn't work for me. They are giving undefined errors.
So I have been looking for an answer to this and have had no luck. Is it possible to send a file to the trash using JXA in Mac Automation? my simple test code looks like this:
// set startup applications that this script will use
var app = Application.currentApplication()
var finder = Application("Finder");
app.includeStandardAdditions = true
function openDocuments(droppedItems)
{
// Variables
var AllFiles = [] // array to store all files in.
for (var item of droppedItems)
{
AllFiles.push(item) // load each file into array
}
// go through each file in the list
for (var i = 0; i < AllFiles.length; i ++)
{
// move to the trash
finder.move(Path(AllFiles[i]), {
to: Path("/Users/usr/.trash"),
replacing: true
})
}
}
this is just a test I am building that should send whatever file I drop onto it to the trash, but it does not recognize .trash as a valid folder location. I have tested it with other folder and that does work so I am assuming that .trash is locked.
I think you need a reference to the trash folder via pathTo command of Standard Additions
For example, to send the currently selected file in the Finder to the Trash, something like this could work.
(() => {
const
ca = Application.currentApplication(),
sa = (ca.includeStandardAdditions = true, ca),
app = Application('Finder'),
seln = app.selection();
app.delete(seln[0])
})();