Get first and last name on Windows with Electron - javascript

I'm have problems with get the first name and last name with electron and node js, i have the username, but i need first name and last name.
Image example
I tried:
const username = require('username');
const os = require ('os');
const computerName = os.hostname();
const fullname = require('fullname');
console.log(os.userInfo());
// Console:
//{ uid: -1,
// gid: -1,
// username: 'mauroh',
// homedir: 'C:\\Users\\mauroh',
// shell: null
//}
console.log("computerName: ", computerName);
console.log("username: " , username());
// Console:
// computerName: DEV
// username: mauroh
fullname().then(name => {
console.log(name);
});
// Console:
// mauroh
Is there any way to get the first and last name? or profile name with electron or node js ?
Example: Mauro HUC
Note: This app is only for windows.
Thanks!

The "fullname" module does in some cases not return the name as it can't be found. This is clearly stated in the GitHub repository for the module.

I found a way to do it,
I am using the username package to obtain the logged-in user.
async getUsername() {
return await username();
}
Then in node js and electron you can use the child processes, child_process docs.
When you perform the command net user <username> or net user <username> / domain you get all the user information, among all the information is the full name, also the name can be empty.
const child = require('child_process');
let exec = child.exec;
// And make a function for do command
function execute(command, callback){
exec(command, function(error, stdout, stderr){
let result = null;
if(!error){
var splitted = stdout.split("\n");
var username = '';
var fullname = '';
for(var i=0; i < splitted.length; i++){
if(splitted[i].search("User name") != -1){
splitted[i] = splitted[i].replace('User name',' ');
splitted[i] = splitted[i].trim();
username = splitted[i];
}else if(splitted[i].search("Full Name") != -1){
splitted[i] = splitted[i].replace('Full Name',' ');
splitted[i] = splitted[i].trim();
fullname = splitted[i];
}
}
let data = {
username: (username) ? username.toLowerCase() : null,
fullname: (fullname) ? fullname: null
}
result = data;
} else{
result = null;
}
callback(result);
});
};
This way you can get the user's full name.

Related

Execute promise or await with generated string variable

I am building a mongoose query and storing it in a variable call query. The code below shows it
let query = "Product.find(match)";
if (requestObject.query.sortBy) {
query = query.concat(".", "sort(sort)");
const parts = requestObject.query.sortBy.split(":");
sort[parts[0]] = parts[1] === "desc" ? -1 : 1;
}
if (requestObject.query.fields) {
query = query.concat(".", "select(fields)");
const fields = requestObject.query.fields.split(",").join(" ");
const items = await Product.find(match).sort(sort).select(fields); //.populate("category").exec();
/**const items = await Product.find(match).sort(sort).select("-__v"); //.populate("category").exec();**/
}
I am facing an issue when attempting to run a mongoose query that I have generated and stored in a string. When I run it in post man, the response is 200 but no data is returned. Below is a console.log(query) on line 2
what I hope to achieve is to have await or create a new promise execute the content id query variable like shown below
const items = new Promise((resolve) => resolve(query)); //.populate("category").exec();
items
? responseObject.status(200).json(items)
: responseObject
.status(400)
.json({ message: "Could not find products, please try again" });
I will appreciate it very much that and also if you can give me a better way of doing it, I will love that
This doesn't really make sense. You are building a string, not a query. You can't do anything with that string. (You could eval it, but you really shouldn't). Instead, build a query object!
let query = Product.find(match);
if (requestObject.query.sortBy) {
const [field, dir] = requestObject.query.sortBy.split(":");
const sort = {};
sort[field] = dir === "desc" ? -1 : 1;
query = query.sort(sort);
}
if (requestObject.query.fields) {
const fields = requestObject.query.fields.split(",");
query = query.select(fields);
}
//query.populate("category")
const items = await query.exec();
if (items) {
responseObject.status(200).json(items)
} else {
responseObject.status(400).json({ message: "Could not find products, please try again" });
}
If you really want to get that string for something (e.g. debugging), build it separately from the query:
let query = Product.find(match);
let queryStr = 'Product.find(match)';
if (requestObject.query.sortBy) {
const [field, dir] = requestObject.query.sortBy.split(":");
const sort = {[field]: dir === "desc" ? -1 : 1};
query = query.sort(sort);
queryStr += `.sort(${JSON.stringify(sort)})`;
}
if (requestObject.query.fields) {
const fields = requestObject.query.fields.split(",");
query = query.select(fields);
queryStr += `.select(${JSON.stringify(fields)})`;
}
//query.populate("category")
//queryStr += `.populate("category")`;
console.log(queryStr);
const items = await query.exec();
…

How does one parent a channel to a category with a discord bot?

Basically there is no errors in the output but at the same time it's not doing what I'm trying to achieve.
Ive been tinkering with the script for 5 hours straight mixing up line positioning and now I got it to where it gives me the promise (my initial issue) but I cant parent the channel.
I've tried discord.js server and site, youtube, 2 other sites i forgot the name of but i cant crack it.
function setup(arguments, message){
var server = message.guild;
var name = message.author.username;
let searchquery = arguments.join("")
let cat = server.createChannel("Important", "category");
async function Channelmaker(Sent, obj){
try {
let chan = await server.createChannel(Sent, "Text");
//console.log(obj);
return chan
} catch(prom){
var chan2 = await server.createChannel(Sent, "Text");
return new Promise(resolve => {
var chan2 = server.createChannel(Sent, "Text", parent = obj);
resolve(chan2)
});
}
}
var holding
var chan = Channelmaker("⚖️ rules ⚖️", cat).then(value => {
console.log(value)
holding = value
value.parentID = cat
chan.setParent(cat.Id)
}).catch(error => {
// s
});
console.log("holding")
console.log(holding)
}
The category is not the parent of the "⚖️ rules ⚖️" channel that is created which is the opposite of what I'm trying to achieve
In Guild.createChannel(), use the options parameter including ChannelData, like so:
await server.createChannel(Sent, {
// You can omit the 'type' property; it's 'text' by default.
parent: obj
});

How to run a javascript function that checks if a username is available

I'm building a javascript function that receives an input and checks it against stored objects in an array to see if it matches against any
The if else statement don't work
const accounts = []; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
let match = (toMatch) => toMatch === newuser.username
if (accounts.some(match) === true) {
return alert("choose another `username");
}
accounts.push(newuser)
return alert("account created")
};
var clik = document.getElementById("login").addEventListener("click", getinput);
It should tell the user if a username is available or not
The direct answer to your question would be along the lines of:
function getInput() {
/* store the value of the input */
var current_userName = document.getElementById("username").value;
/* check if that value already exists in the accounts Array */
var matched = accounts.find(account => account.username === current_userName);
/* conditional for each of the two cases */
if (!matched) {
/* code if username is available */
} else {
/* code if username is NOT available */
}
};
document.getElementById("login").addEventListener("click" , getInput);
You have some mistakes in your code, which need fixing.
Also, look into Array.prototype.find() for more info.
Hope this will help you get started in the right direction. Best of luck!
Finally understood what I was doing wrong had to point toMatch of accounts to check for username contained within the array of object
const = [ ]; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
//this was where I got it wrong I was doing toMatch === newuser.username which was wrong
let match = (toMatch) => toMatch.username === user
if (accounts.some(match) === true) {
return alert("choose another username");
}
accounts.push(newuser)
return alert("account created")
};
document.getElementById("login

why my alert shows undefined in javascript

var database = require('../../db');
var rightponame = '1';
var rightdevname = '';
var rightpopassword = '';
var rightdevpassword = '';
database.db.once('open', function() {
console.log('success');
var cursor = database.db.collection('user').find({}, {
_id: 0
});
cursor.each(function(err, doc) {
if (doc != null) {
rightponame = doc.productOwner;
rightdevname = doc.developer;
rightpopassword = doc.popassword;
rightdevpassword = doc.devpassword;
console.log(rightponame);
console.log(rightdevname);
console.log(rightpopassword);
console.log(rightdevpassword);
} else {
console.log('o');
}
});
});
function login() {
var getusername = document.getElementById("username").value;
var getpassword = document.getElementById("password").value;
alert(rightponame);
}
Finally, I get rightponame, rightdevname, rightpopassword and rightdevpassword value. But in the login function, I get undefined in the alert.
Why?
In JavaScript, alert is only available in the browser. It appears you're using node.js or the like. Try console.log instead, as you're doing on db open.
Then when you check the terminal window where the process is running, you should see the value of console.log.
Since console.log takes multiple values, it's helpful to prefix with something distinguishable like:
console.log('<<<<<<<', rightponame)

node.js only passing filled out values to mongodb

I'm working on a project in node.js, mongodb, and express that has to deal with transactions.
I can hard code the variables to be put into mongodb, but if not all the fields are being filled out (not all are required) then I'm just putting empty data into the database.
this code works:
var d = new Date();
var n = d.toJSON();
var date = n;
var address = req.body.property_address;
var client_name = req.body.client_name;
var sales_price = req.body.sales_price;
var commission_percent = req.body.commission_percent;
var referral = req.body.referral;
var donation = req.body.donation;
var client_source = req.body.client_source;
var client_type = req.body.client_type;
var notes = req.body.notes;
Transaction.findOne({ name: { $regex: new RegExp(date, "i") } },
function(err, doc){
if(!err && !doc) {
console.log("there is no error, and this does not already exist");
var newTransaction = new Transaction();
newTransaction.date = date;
newTransaction.address = address;
newTransaction.client_name = client_name;
newTransaction.sales_price = sales_price;
newTransaction.commission_percent = commission_percent;
newTransaction.referral = referral;
newTransaction.donation = donation;
newTransaction.client_source = client_source;
newTransaction.client_type = client_type;
newTransaction.notes = notes;
newTransaction.save(function(err) {
if(!err){
console.log("successfully saved");
res.json(200, {message: newTransaction.date});
} else {
res.json(500, {message: "Could not create transaction. Error: " + err})
}
});
}
});
But what's the point of putting in a value that doesn't exist into mongodb? Isn't that one of the things that is supposed to be awesome about it? And my thinking is, it takes away possible queries that I might be able to do in the future.
Would it be possible to do something more like this?
Transaction.findOne({ name: { $regex: new RegExp(date, 'i' ) } },
function(err, doc){
if(!err && !doc){
var newTransaction = new Transaction();
for(var key in req.body){
newTransaction.key = req.body[key];
}
}
}
});
update
This is the code I ended up using that worked.
Transaction.findOne({ name: { $regex: new RegExp(date, "i") } },
function(err, doc){
if(!err && !doc){
var newTransaction = new Transaction();
for(var key in req.body){
if(req.body[key] != ''){
newTransaction[key] = req.body[key];
}
}
}
}
});
This is perfectly fine behaviour. You can still query a field that doesn't exist in all documents, as a non-existent field is the same as not equal.
This means the loose definition of the documents is still retained.
Looks fine to me, but I would probably not want to trust just ANY client data to serve as key, depending on how you deploy.
Perhaps:
['date', 'address', 'client_name'/*,...*/].forEach(function(key)
{
/* ... */
if (key in req.body) newTransaction[key] = req.body[key];
});

Categories

Resources