I'm trying to make it possible to choose different SSID's to switch the Wlan you are connected to from Browser.
var sys = require('sys');
var exec = require('child_process').exec;
app.get(prefix + '/wlan', function(req, res){
child = exec("iwlist wlan0 scan | grep ESSID", function(error, stdout, stderr){
if(error !== null){
console.log('Exec error ' + error);
}
else {
res.send(stdout);
}
});
});
This is my code so far to get a SSID list..
The Output is like that:
ESSID:"WLAN-GUEST" ESSID:"WLAN1" ESSID:"WLAN-GUEST" ESSID:"WLAN1" ESSID:"WLAN2"
I have no idea why two ESSID's are listed twice but my main question is, how can I parse this to JSON or how can I access each entry like an array (wlanlist[0])?
Edit:
I tried to stdout.replace(" ",", "); and JSON.parse but as it's async it's sent without changes. (Not sure if that would work as sync)
Edit2: Trying to access the data like that:
$(document).ready(function() {
$.get(prefix + '/wlan', function(wlanlist){
document.getElementById("wlanoptions").options[0] = new Option("Select your WLAN:","");
document.getElementById("wlanoptions").options[1] = new Option(wlanlist[0],wlanlist[0])
});
});
Final Result:
var wlanlistarray = stdout.split("ESSID:");
res.send(wlanlistarray);
In addition:
//extract ssid and remove quotes
var wlanlist = new Array;
var step1 = stdout.split("ESSID:");
for(i = 1; i < step1.length; i++){
var arr = new Array;
arr = step1[i].split('"');
//if exists in array -> continue; else create new entry in wlanlist
if(wlanlist.indexOf(arr[1]) === -1){wlanlist.push(arr[1]);}
else{continue;}
}
res.send(wlanlist);
This should return an array of SSIDs:
stdout.split("ESSID:")
Now clean up the " and you are all done.
Related
I'm trying to write a script that allows me to search for a string in a number of folders and then return the output. I've managed to find the readdirSync function which does what I want, however I am unable to print out the total number of strings found because it is ran before the function is complete. Please see example below.
var totalNumberOfStringFound = 0;
function numberofStringsInFolder(dir, search) {
var fs = require('fs');
var results = [];
var searchTerm = search;
fs.readdirSync(dir).forEach(function (file) {
file = dir + '/' + file;
var stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(numberOfTagsInFolder(file));
} else {
fs.readFile(file, bar);
function bar(err, data) {
err ? Function('error', 'throw error')(err) : (fileContent = data.toString('utf8'));
var count = (fileContent.match(new RegExp(searchTerm, 'gi')) || []).length;
totalNumberOfStringFound = totalNumberOfStringFound + count;
console.log('NUMBER OF STRINGS FOUND: ' + totalNumberOfStringFound);
}
// Holds the list of files found
results.push(file);
}
});
console.log("totalNumberOfStringFound: " + totalNumberOfStringFound);
return results;
}
numberofStringsInFolder('./folder', 'HELLO');
Output
totalNumberOfStringFound: 0
NUMBER OF STRINGS FOUND: 2
NUMBER OF STRINGS FOUND: 3
The output (totalNumberOfStringFound) should be 3, but because totalNumberOfStringFound is called before the function has finished, it is showing as 0. I've looked online and some people use the timeout function, but I don't want to use that because I don't know how long it will take to complete. I would really appreciate it if someone can help. Thank you
I'm trying to build a search page, I want to build a "find query" by the criterions the client filing.
How can I do this?
I have tried to build a query string in js but it doesn't work, then I tried to build a dictionary of the criterions, criterionName : criterionValue also not worked
var query = req.body.query;
console.log("Connected To Server");
var mydb = db.db('');
var docToSearch = mydb.collection('docs');
docToSearch.find(query)
.toArray(function(err,result){
return res.send(result);
});
}
function GetSearchQuery(criterionsToSearch){
let query = [];
criterionsToSearch.forEach(function(criterion, index){
let input = $("input[data-criterion='" + criterion + "']");
let select = $("select[data-criterion='" + criterion + "']");
let criterionName,criterionValue;
if(input.length) {criterionName = $(input).attr("name"); criterionValue = $(input).val(); }
if(select.length) {criterionName = $(select).attr("name"); criterionValue = $(select).val();}
query.Add({criterionName:criterionValue});
});
return query;
}
I have nodejs-mongo setup with db configured as follows (only one entry shown here)
{
"filename":"type1.json","secs":72.4060092977,"platform":"mac","version":"1.3.0", "inputfile":"temp.mov"
},
Here are the mongo commands I am trying to replicate
db.perfR.distinct("platform") * (output: ["mac", "win"] ) *
db.perfR.distinct("version",{"platform":"win"}) * (output: ["1.3.0", "1.3.2"] ) *
db.perfR.find({"version":1.3.2,"platform":"win"},{"filename":1,"secs":1,"_id":0}) * (output: ["filename":"type1.json","secs":72.4060092977] ) *
So what I am trying to do is
for every platform
for every version
get filename
get secs
Here is the code I have written thus far
function createPlatformDataSets(callback){
var dbHost = "mongodb://mongo:27017/perfSample";
var mongodb = require('mongodb')
var platformDataSets = []
var platformq = "platform"
//get Instance of Mongoclient
var MongoClient = mongodb.MongoClient;
//Connecting to the Mongodb instance.
//Make sure your mongodb daemon mongod is running on port 27017 on localhost
MongoClient.connect(dbHost, function(err, db){
if ( err ) throw err;
//use the distinct() to retrive distinct platforms
db.collection("perfR").distinct(platformq,function(err, platResultSet){
if ( err ) throw err;
var maxPlatCnt = platResultSet.length // 1
if (maxPlatCnt == 0){
console.log("Bad PlatfQ Query")
callback(true)
}
var versionedPlatDataSet = 0
for (p=0; p < platResultSet.length; p++){
(function(index){
var platform = platResultSet[index]
var options = createOptions(platform);
//Get Versions
var versionq = "\"version\",{\"platform\":" + platform + "}"
console.log("Versionq::"+versionq)
var dataSets = [];
//var versions = ["1.3.0", "1.3.2"]; // (select disctinct(version) from cpu where platform = plat)
// Use distinct() to find distinct Versions
db.collection("perfR").distinct(versionq,function(err, verResultSet){
if ( err ) throw err;
var maxVerCnt = verResultSet.length // 2
if (maxVerCnt == 0){
db.close()
console.log("Bad Versionq Query")
callback(true)
}
var dataSetResponseCnt = 0
for ( v=0; v < verResultSet.length; v++){
(function(idx){
var dataq = "{platform:" + platform + ",version:" + version + "},{filename:1,secs:1,_id:0}"
// Use find() to find filename and secs for given version and platform
db.collection("perfR").find(dataq,function(err, dataResultSet){
if ( err ) throw err;
if (dataResultSet.length == 0){
console.log("Bad dataq Query")
callback(true)
}
//do something with filename and secs
dataSetResponseCnt++
if (maxVerCnt == dataSetResponseCnt){
var platformData = {"options":options, "labels":labels, "datasets":dataSets, "platform":platform}
platformDataSets.push(platformData)
if (versionedPlatDataSet == maxPlatCnt){
db.close()
callback(null,platformDataSets)
}
}
})
})(v)
}
versionedPlatDataSet++
})(p)
}
}
}
At "1" I am able to retrive distinct platforms
But at "2" I get verResultSet.length to be zero.
Can someone point to me what is wrong?
(PS: This is my first serious async problem with javascript so bear with my code. All suggestions are welcome :) )
you can use Promises. so for example your code is going to be something like this:
return loadPlatforms().then(function (res){
res.map(function(platform){
loadVersion(platform).then(...)
}
})
Your use of .distinct() isn't correct. You are passing a JSON-like string when the API actually takes two separate arguments (not including the callback). So the real code should in fact just be more or less what you originally showed:
var query = { platform: 'win' };
db.collection('perfR').distinct('version', query, function(err, verResultSet) {
// ...
});
I have a config.js file which I believe is JSON which is called when the application first starts:
var config={};
config.user = [
{id:'JSMITH', priceModify:'true'},
{id:'JBLOGGS', priceModify:'false'},
]
config.price = [
{id:"price01", name:"priceName01", primary:"57.25", secondary:"34.54"},
{id:"price02", name:"priceName02", primary:"98.26", secondary:"139.45"},
{id:"price03", name:"priceName03", primary:"13.87", secondary:"29.13"}
]
To pull / push data I just use the following:
// Read
var curPrice = config.price[0].primary;
// Write
config.price[0].primary = "98.24";
How do I go about exporting the config file with the new value so that it will load next time the application is opened? I can use the file system object to write the file, I just don't understand how I would export everything (and preferably keep the same format).
I originally thought about reading the whole config file into a variable, cycling through to find the required block, id, and key and replacing the value, then writing the whole thing back, but I can't seem to figure out how to replace that specific value only.
Any help would be greatly appreciated
Edit Apologies, I forgot to mention that this application is completely offline and uses local directories
Solution
I stumbled across a few solutions to different issues which, when combined, gave me the perfect solution. First we cycle the Javascript object, building an array of the detail and then converting the array to a string:
vMethod.convertToText = function(obj) {
var string = [];
var output = '';
var count= 0;
var countTotal = 0;
if (typeof(obj) == "object" && (obj.join == undefined)) {
count= 0;
countTotal = 0;
string.push("{");
for (prop in obj) {
countTotal++;
}
for (prop in obj) {
if(count==countTotal - 1) {
string.push(prop, ": ", vMethod.convertToText(obj[prop]),'}\r\n');
} else {
string.push(prop, ": ", vMethod.convertToText(obj[prop]), ",");
}
count++;
};
} else if (typeof(obj) == "object" && !(obj.join == undefined)) {
count= 0;
countTotal = 0;
string.push("[\r\n")
for (prop in obj) {
countTotal++;
}
for(prop in obj) {
if(count==countTotal - 1) {
string.push(vMethod.convertToText(obj[prop]),'];\r\n');
} else {
string.push(vMethod.convertToText(obj[prop]), ",");
}
count++;
}
} else if (typeof(obj) == "function") {
string.push(obj.toString())
} else {
string.push(JSON.stringify(obj))
}
output = string.join("").toString();
//output = output.slice(1, -1);
return output;
}
Then we clean the array (neccessary for me to remove excess characters)
vMethod.cleanConfigText = function() {
var outputText = vMethod.convertToText(config);
outputText = outputText.slice(1, -1);
outputText = 'var config = {};\r\n'+outputText;
outputText = outputText.replace('user:','config.user =');
outputText = outputText.replace(',price:','config.price =');
outputText = outputText.slice(0, -2);
outputText = outputText.replace(/"/g, "'")
return outputText;
}
Finally a function to export the object into my config.js file:
vMethod.writeToConfig = function() {
vObject.fileSystem = new ActiveXObject('Scripting.FileSystemObject');
vObject.fileSystemFile = vObject.fileSystem.CreateTextFile('source\\js\\config.js',true);
vObject.fileSystemFile.Write(vMethod.cleanConfigText());
vObject.fileSystemFile.Close();
delete vObject.fileSystemFile;
delete vObject.fileSystem;
}
So when I want to export a change in the config, I just call:
vMethod.writeToConfig();
The only difference in the file format is that the commas appear at the start of a trailing line rather than the end of a preceding line but I can live with that!
Edit Turns out I'm anally retentive and the commas were bugging me
Added these to the clean up function and now the config is identical to before but without the indent
outputText = outputText.replace(/[\n\r]/g, '_');
outputText = outputText.replace(/__,/g, ',\r\n');
outputText = outputText.replace(/__/g, '\r\n');
Thank you to those that looked at the question and tried to help, very much appreciated.
Edit
DO NOT READ THE SOLUTION ABOVE, IT IS IN THE WRONG PLACE AND THERFORE IS NOT A VALID ANSWER. YOU'VE BEEN WARNED.
You can use a very popular npm package: https://www.npmjs.com/package/jsonfile . There are many but I've choosen this one.
Usually config stuff should be in json or .env files.
Now, all you have to do is use jsonfile's API to read/write JSON and parse (the package does the serialization/deserialization) it at the beginning when the application starts.
Example:
var jsonfile = require('jsonfile');
var util = require('util');
var config = null;
var file = './config.json';
// Reading
jsonfile.readFile(file, function(err, obj) {
config = obj;
});
// Writing
// Edit your config blah blah
config.user = [
{id:'JSMITH', priceModify:'true'},
{id:'JBLOGGS', priceModify:'false'},
];
config.price = [
{id:"price01", name:"priceName01", primary:"57.25", secondary:"34.54"},
{id:"price02", name:"priceName02", primary:"98.26", secondary:"139.45"},
{id:"price03", name:"priceName03", primary:"13.87", secondary:"29.13"}
];
jsonfile.writeFile(file, config, function (err) {
if(err) return err;
console.log('Config saved to file!');
});
I'm trying to retrieve all data from a db table into json object, like so:
function getTableData()
{
var vals = {};
var data = [];
try {
var dbCon = $.db.getConnection();
var query = 'SELECT * FROM SAPPRD.ZUSERDATATAB';
var pstmt = dbCon.prepareStatement(query);
var rs = {};
rs = pstmt.executeQuery();
while (rs.next()) {
vals.team = rs.getString(1);
vals.fname = rs.getString(3);
vals.lname = rs.getString(2);
data.push(vals);
$.response.status = $.net.http.OK;
}
$.response.setBody(JSON.stringify(data));
// $.response.contentType = contentType;
// $.response.headers.set('Content-Disposition', 'filename=' + filename);
} catch (e) {
$.response.setBody('errors: ' + e.message);
}
}
The query works only partially, because in data I get number of rows x last row content, like so:
[{"team":"I313766","fname":"0","lname":"LEGOWSKI"},
{"team":"I313766","fname":"0","lname":"LEGOWSKI"},
etc. etc.]
How would I make it retrieve all the data instead of one row number of times?
Okay, I got the solution. Moving a single line declaring array vals into the while statement solved the problem - the array vals was initialized as an empty array each time, therefore allowing the proper .push of each row, instead of pushing last row from db table into data multiple times. Thanks to everybody who took time and tried answering.
function getTableData()
{
var data = [];
try {
var dbCon = $.db.getConnection();
var query = 'SELECT * FROM SAPPRD.ZUSERDATATAB';
var pstmt = dbCon.prepareStatement(query);
var rs = pstmt.executeQuery();
while (rs.next()) {
var vals = {}; // this is the moved line of code...
vals.team = rs.getString(1);
vals.fname = rs.getString(3);
vals.lname = rs.getString(2);
data.push(vals);
$.response.status = $.net.http.OK;
}
$.response.setBody(JSON.stringify(data));
// $.response.contentType = contentType;
// $.response.headers.set('Content-Disposition', 'filename=' + filename);
} catch (e) {
$.response.setBody('errors: ' + e.message);
}
}
solution above just in case someone needs it in future.
This is XSJS(server side JS) and not SAPUI5. The read of DB is pretty similar to the JDBC framework in Java to read DB tables and the result set collection will have the data and you iterate over them and move them to a local object.
There is only call to the DB during execute_query and rs.next() is just a loop to read each row.