Searching pages in Electron? - javascript

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!

Related

Directus v9 file-type validations before upload

Is there any way to validate or limit what file-type/ extensions could be uploaded before it actually gets uploaded?
I've tried using a couple of custom-hooks but they all just went through.
Hooks tried:
files.create.before
items.create.before
module.exports = function registerHook({ exceptions }) {
const { InvalidPayloadException } = exceptions;
return {
"files.create.before": async function (input) {
console.log(input);
throw new InvalidPayloadException("title");
},
};
};
If you scroll down past either Filter, or Action Events, you will see a small block listing all system collection names where files cannot be intercepted during create/update.
Maybe they're trying to keep it as a file manager which can store every types, then bind it through pivot table.
You could try creating a custom user interface where you limited the choice of uploading file extensions yourself (Not sure if it works).
enter image description here

expo- react native : there is way to see the content of the expo FileSystem and also delete content from there?

there is way to see the content of the FileSystem and also delete content from there?
i have data inside the expo FileSystem and i need :
look inside FileSystem because i dont know how to find this file because i work with the expo client sdk with the qr code scan and i dont understand how can i find this file there .
i want to know how to delete contents from the file system .
how can i see the sqlite database as a real table ?
this is my examle :
saveDbData = async () => {
const { data, isLoaded } = this.state;
for (let i = 0; i < data.length; i++) {
const mediaData = data[i];
const dbResult = await insertPlace(
mediaData.artist,
mediaData.image,
mediaData.title,
mediaData.url
);
console.log("SQL", `${FileSystem.documentDirectory}/SQLite/places.db`);
}
const fetchawesome = await fetchPlaces();
console.log(fetchawesome)
};
Since there are three questions from your part, I'll try to answer them one by one and provide a possible solution.
look inside FileSystem because i dont know how to find this file
because i work with the expo client sdk with the qr code scan and i
dont understand how can i find this file there .
You can access the file system using the FileSystem package from expo. Here's how you can do it. Import the package first.
import * as FileSystem from "expo-file-system";
Then you can find the URI of the file like this.
const { uri } = await FileSystem.getInfoAsync(
`${FileSystem.documentDirectory}SQLite/${"yourDB.db"}`
);
I want to know how to delete contents from the file system.
You can delete a file if you have access to its location or URI. This is how you can delete it. It returns a promise.
FileSystem.deleteAsync(fileUri)
how can I see the SQLite database as a real table?
This is a tricky part because since you're using your android phone to run the application via expo, you won't have direct access to your db. One thing you can do is to move the db to someplace else where you have access to and using the Sharing API from expo to save or send the db to yourself via email or any other way.
import * as Sharing from "expo-sharing";
let documenturi = `${FileSystem.documentDirectory}/yourDB.db`;
await FileSystem.copyAsync({
from: uri,
to: documenturi,
});
Sharing.shareAsync(documenturi);
You can make this as a function which fire's on a Button press on you can even put this in useEffect or lifecycle methods to fire up when the screen loads.

How can i create an array as a database with JSON files and use Javascript to update / save it

I am making a discord bot in Node.js mostly for fun to get better at coding and i want the bot to push a string into an array and update the array file permanently.
I have been using separate .js files for my arrays such as this;
module.exports = [
"Map: Battlefield",
"Map: Final Destination",
"Map: Pokemon Stadium II",
];
and then calling them in my main file. Now i tried using .push() and it will add the desired string but only that one time.
What is the best solution to have an array i can update & save the inputs? apparently JSON files are good for this.
Thanks, Carl
congratulations on the idea of writing a bot in order to get some coding practice. I bet you will succeed with it!
I suggest you try to split your problem into small chunks, so it is going to be easier to reason about it.
Step1 - storing
I agree with you in using JSON files as data storage. For an app that is intended to be a "training gym" is more than enough and you have all the time in the world to start looking into databases like Postgres, MySQL or Mongo later on.
A JSON file to store a list of values may look like that:
{
"values": [
"Map: Battlefield",
"Map: Final Destination",
"Map: Pokemon Stadium II"
]
}
when you save this piece of code into list1.json you have your first data file.
Step2 - reading
Reading a JSON file in NodeJS is easy:
const list1 = require('./path-to/list1.json');
console.log(list.values);
This will load the entire content of the file in memory when your app starts. You can also look into more sophisticated ways to read files using the file system API.
Step3 - writing
Looks like you know your ways around in-memory array modifications using APIs like push() or maybe splice().
Once you have fixed the memory representation you need to persist the change into your file. You basically have to write it down in JSON format.
Option n.1: you can use the Node's file system API:
// https://stackoverflow.com/questions/2496710/writing-files-in-node-js
const fs = require('fs');
const filePath = './path-to/list1.json';
const fileContent = JSON.stringify(list1);
fs.writeFile(filePath, fileContent, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
Option n.2: you can use fs-extra which is an extension over the basic API:
const fs = require('fs-extra');
const filePath = './path-to/list1.json';
fs.writeJson(filePath, list1, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
In both cases list1 comes from the previous steps, and it is where you did modify the array in memory.
Be careful of asynchronous code:
Both the writing examples use non-blocking asynchronous API calls - the link points to a decent article.
For simplicity sake, you can first start by using the synchronous APIs which is basically:
fs.writeFileSync
fs.writeJsonSync
You can find all the details into the links above.
Have fun with bot coding!

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.

Javascript Logging function

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
}

Categories