Javascript Logging function - javascript

For a little project I'm coding besides my job I wanted to make a log function so I can output simple things into a textfile like the user input and possible errors that occured.
I wanted to make this log a simple .txt.
The problems I ran into were the following:
I want to check if the file already exists if not, create a new one;
Then when the file exists I want to write below the existing contents.
This is what I got so far:
/*
Form:
\r\n
\r\n *** logged (<dd.mm.yyyy> || <hh:mm:ss>) ***
\r\n
\r\n <pMessage>
\r\n
\r\n *** log end ***
*/
function log(pMessage)
{
var logPath = "../../Logs/SiteLog.txt";
}
I know it is not much because I haven't done anything there yet. So i basically need three things: Checking if the file exists, creating a file, editing the file.
Thanks in advance for your help.

If this is client side, the browser will prevent you from writing to the file system. If this is strictly for your own testing purposes locally, you could write to window.localStorage
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
This would allow you to read and write from a local storage that the browser caches based on domain
function read (name) {
return window.localStorage.getItem(name)
}
function write (name, value) {
var report = window.localStorage.getItem(name) + '\n' + value
window.localStorage.setItem(name, report)
return report
}

Related

net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.EcmaError: ReferenceError: "java" is not defined. (internal#105)

When trying to invoke a JNLP application with Open Web start , I get this stack trace of errors.
net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.EcmaError: ReferenceError: "java" is not defined. (internal#105)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3557)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3535)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.notFoundError(ScriptRuntime.java:3620)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.ScriptRuntime.name(ScriptRuntime.java:1652)
at net.adoptopenjdk.icedteaweb.shaded.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:3413)
at script.dnsResolve(internal:105)
at script.getResolvedIp(http://uhic.ca.edu/toodeepregression3.pac:569)
at script.FindProxyForURL(http://uhic.ca.edu/toodeepregression3.pac:62)
The script at line 569 is..
internalResolvedIp = dnsResolve(host)
if (
host
) {
// If the user has typed an IP address in the address bar, take it
// as it is.
var isIpV4Address = /^(\d+.){3}\d+$/;
var isIpV6Address = /^\[(.*)\]$/;
if (
isIpV4Address.test(host)
) {
internalResolvedIp = host;
} else {
var matches = host.match(isIpV6Address);
if (
matches && matches.length === 2
) {
// Get the address between the square brackets
internalResolvedIp = matches[1];
} else if (
isDnsResolvingAllowed
) {
****internalResolvedIp = dnsResolve(host);****
}
}
}
I am not sure what this error is . I have looked at the Open web start logs as well . I have searched far and wide in the itnernet world but I barely get any hits for this error.
You have clearly hit the Bug, I am trying to resolve in OWS for my Team as well. We have been stuck with this issue for 9 months ever since OWS rolled out.
I can explain you what I discovered so far. Infact I sent my sanitized pac-proy to OWS team to identify the issue but they sent it back to me .
So here is the issue.
OWS has a javascript file in its source code. When you call dnsResolve in your pac-proxy, it invokes the provider of dnsResolve and that implementation is in OWS source code.
Now the dnsResolve call java.net.* package classes internally. This requires Rhino and Java interface to have been stabilized at run time.
OWS is not able to create that interface connection so when javascript tries to call java through the Rhino interface , it can not find java classes since it can not recognize that interface and so comes back to say java not found.
I and my Team are still analyzing the wireshark logs of error to figure out how we could put a fix into OWS or understand how OWS ,Java and Rhino can be successfully talk to each other in the security sandbox container inside which OWS runs.
I could not give u a solution but a better understanding as to where you would like to put your efforts to make it work for u.

Discord User History - Saving Multiple Things In A JSON File

I'm trying to set up a history command for when a player gets warned with a moderation bot. I have it where it saves it in a JSON file however I don't know how to save multiple cases for one player. Right now it just replaces the last warn.
//--Adds To Logs
let warnhist = JSON.parse(fs.readFileSync("./historywarn.json", "utf8"));
warnhist[wUser.id] = {
Case: `${wUser} was warned by ${message.author} for ${reason}`
};
fs.writeFile("./historywarn.json", JSON.stringify(warnhist), (err) => {
if (err) console.log(err)
});
It saves like this without adding onto it every time:
{"407104392647409664":{"Case":"<#407104392647409664> was warned by <#212770377833775104> for 2nd Warn"}}
I need it to save like this:
{
"407104392647409664":{"Case":"<#407104392647409664> was warned by <#212770377833775104> for 1st Warn", "Case 2":"<#407104392647409664> was warned by <#212770377833775104> for 2nd Warn" }
}
You want an array instead of an object. Try structuring your data a bit more too, so your JSON looks like this:
{ "<user id>": { "warnings": [...] }
Then instead of overriding the history every time with an assignment warnhist[wUser.id] = ... you can use Array.prototype.push to add a new one.
Taking a step back though, I don't think JSON is a good strategy to store this data, especially if it contains all warnings for all users. You need to load the entire JSON and read the file and write the file every single time you add a warning, and there could be conflicts if you have multiple instances of your service doing the same for a large number of users.
For a super similar API and storage format but better performance and consistency, try MongoDB instead of a plain JSON file.

Searching pages in Electron?

I’m currently working on designing a program in Electron. One of the key parts to this program will be a search option. Similar to other websites that you can search the whole site for pages that match your inquiry, I would like to search within the “pages”/“html files” of my program and have it display the search results. Preferably a letter at a time display in real time so one can see results as they type, but even an option with search will do. I just need to search within my program pages, not an external site. I’m having trouble figuring out how to get started implementing this, since PHP isn’t supported in Electron. I know react can do the letter at a time real time searching, but I’m not sure how to do the search of other pages or how to parse them for searching. Any suggestions, guidelines, or frameworks to get me on the right track would be helpful. Thanks!
EDIT: I’m also aware of the webcontents.findInPage() function, but that only searches the current page, not other pages in the project path. I am fine defining which pages to search manually if I can find a way to actually search them.
If you store all your pages in a directory like "views" you can use fs to read each file and search its content.
I have made a quick example of something you could make to do this:
// The directory containing all your pages
let directoryToYourPagesOrHTMLFiles = "/your/directory/";
// Require fs so you can get all the files and file content
const fs = require("fs");
// Require html-to-text so you can parse the HTML in the files
// into text so you can search on the data easier
let htmlToText = require('html-to-text'); // npm install --save html-to-text
// Run this function when a user enters a character
function userTyped(inputValue) {
// Foreach file in the directory
fs.readdir(directoryToYourPagesOrHTMLFiles).forEach(filename => {
// Read the file contents
fs.readFile(directoryToYourPagesOrHTMLFiles + "/" + filename, "utf8", (err, data) => {
// If there was an error reading the file log it
if(err) {
console.log(err);
} else {
// If there was no error, parse the HTML into text
let text = htmlToText.fromString(data);
// Perform your search on the next using the inputValue
// Example Search:
if(text.indexOf(inputValue) > -1) {
// Display the page in your search results
displaySearchResult(directoryToYourPagesOrHTMLFiles + "/" + filename);
}
}
});
});
}
function displaySearchResult(pagePath) {
/*
Add the page to a results page
*/
}
I didn't test this because it did it in a rush but it shows the concept of what you need to do!
Hope this helps you!

Lotus notes automation from browser

I have been trying to automate Lotus Notes mail fillup from a browser interface.
After refering to Richard Schwartz's answer, i came up with this piece of code using the Lotus.NotesSession class.
function SendScriptMail() {
var mToMail = document.getElementById('txtMailId').value
var mSub = document.getElementById('txtSubject').value
var mMsg = document.getElementById('txtContent').value
var Password = "yyy"
alert("1");
var MailFileServer = "xxx.com"
var MailFile = "C:\Program Files\IBM\Lotus\Notes\mail\user.nsf"
alert("2")
var Session;
var Maildb;
var UI;
var NewMail;
var From = "user#xxx.com"
try {
alert("3")
// Create the Activex object for NotesSession
Session = new ActiveXObject("Lotus.NotesSession");
alert("4")
if (Session == null) {
throw ("NoSession");
} else {
Session.Initialize(Password);
// Get mail database
Maildb = Session.GetDatabase(MailFileServer, MailFile);
alert("5")
if (Maildb == null) {
throw ("NoMaildb");
} else {
NewMail = MailDB.CreateDocument();
if (MailDoc == null) {
throw ('NoMailDoc');
} else {
// Populate the fields
NewMail.AppendItemValue("Form", "Memo")
NewMail.AppendItemValue("SendTo", mToMail)
NewMail.AppendItemValue("From", From)
NewMail.AppendItemValue("Subject", mSub)
NewMail.AppendItemValue("Body", mMsg)
NewMail.Save(True, False)
NewMail.Send(False)
}
}
}
} catch (err) {
// feel free to improve error handling...
alert('Error while sending mail');
}
}
But now, alerts 1,2,3 are being trigerrd, and then the counter moves to the catch block. The lotus notes session is not being started.
In a powershell script that I was previously looking at there was a code regsvr32 "$NotesInstallDir\nlsxbe.dll" /s that was used before the Session = new ActiveXObject("Lotus.NotesSession");. Is there something similar in javascript too, if so how do i invoke that dll.
I think I've realised where I am going wrong. According to me, upto alert("5") things are good. But since Lotus.NotesSession doesn't have a CreateDocument() method, it is throwing the error. I am not sure how to create the document and populate the values though.
Since you've chosen to use the Notes.NotesUIWorkspace class, you are working with the Notes client front-end. It's running, and your users see what's happening on the screen. Are you aware that there's a set of back-end classes (rooted in Lotus.NotesSession) instead of Notes.NotesSession and Notes.NotesUIWorkspace) that work directly with Notes database data, without causing the Notes client to grab focus and display everything that you're doing?
Working with the front-end means that in some cases (depending on the version of Notes that you are working with) you're not going to be working directly with the field names that are standard in Notes messages as stored and as seen in the back-end. You're going to be working with names used as temporary inputs in the form that is used to view and edit the message. You can see these names by using Domino Designer to view the Memo form.
Instead of using 'SendTo', try using:
MailDoc.Fieldsettext('EnterSendTo', mToMail)
Regarding the Body field, there's no temporary field involved, however you haven't really explained the difficulty you are having. Do you not know how to display the interface that you want in the browser? Do you not know how to combine different inputs into a single FieldSetText call? Or are you just dissatisfied with the fact that FieldSetText can't do any fancy formatting? In the latter case, to get more formatting capability you may want to switch to using the back-end classes, which give you access to the NotesRichTextItem class, which has more formatting capabilities.

InDesign scripting of the Socket object yields cryptic error message

I'm working on a broadcast e-mail template that would pull the latest three articles off our blog from an RSS feed and insert the relevant sections into the document.
I looked at the documentation, and based on the bit about the File object, some of my own debugging, and an InDesign forum post I've learned that it's not possible to use the File object to source an online XML file.
The alternative (without resorting to an external script, one of which didn't work for me anyways), it seems, is to use the Socket object. So I went back to the documentation and copied/pasted this code verbatim from there:
reply = "";
conn = new Socket;
// access Adobe’s home page
if (conn.open ("www.adobe.com:80")) {
// send a HTTP GET request
conn.write ("GET /index.html HTTP/1.0\n\n");
// and read the server’s reply
reply = conn.read(999999);
conn.close();
}
When I ran it, I received this descriptive error message:
A search for "89858 javascript error" yielded nothing useful.
So I'm stuck. Either Adobe's code sample has an error, or, more likely, there's something wrong on my end. If I had to guess, I'd guess that it's some kind of proxy problem, but I don't know for sure and don't know how to find out.
Can anyone help? The principles of the Socket object make sense to me, but if I can't get even the sample to work, I don't really have anywhere to go with this.
The error above occurs when you return certain objects (XML, Socket) from a function call, but the return values does not get assigned anywhere.
function test() {
var xml = new XML('<test />');
return xml;
}
test();
The above will cause an error. To get around it you have to assign the return value somewhere.
var result = test();
Try to put all collect all function calls result. I am not sure which one causes the error.
var reply = "";
var conn = new Socket;
// access Adobe’s home page
if (conn.open ("www.adobe.com:80")) {
// send a HTTP GET request
var result = conn.write ("GET /index.html HTTP/1.0\n\n");
// and read the server’s reply
reply = conn.read(999999);
var close = conn.close();
}

Categories