Replace particular file content in nodejs - javascript

I want to replace a particular line using javascript with new content.
This is the file content,
SERVER=1055#localhost
GROUP_SERVERS=2325#localhost
LINE_IAM_INTERESTED=KTYUIERVW:2800
FILE_PATH="C:\Program Files\somefile\Shared Files\"
In this line, LINE_IAM_INTERESTED=KTYUIERVW:2800 .I want to replace KTYUIERVW with KJHTERDY and 2800 with 78945
I have shown what I tried using fs appendfilesync
fs.appendFileSync('file_name').toString().split('\n').forEach(function(line){
app.console.log("called append");
var sEntry = line.split("=");
if (sEntry.length == 2) {
if (sEntry[0] == "LINE_IAM_INTERESTED") {
app.console.log("found one!!!!");
}
}
});

you can try READ -> REPLACE -> WRITE flow:
fs.writeFileSync('file_name', fs.readFileSync('file_name').replace('KTYUIERVW:2800', 'KJHTERDY:78945'))

appendFile and appendFileSync are used for adding to the end of the file. Although you can do it as a one liner as shown in the other answer, I've kept the structure of your code the same. Here you want to read the data, modify it then re-write it. Using the block of code you have, you can modify it to use readFileSync and writeFileSync.
let newData = fs.readFileSync('file_name', 'utf-8').split('\n').map(line => {
let sEntry = line.split('=')
if (sEntry.length == 2) {
if (sEntry[0] == "LINE_IAM_INTERESTED") {
console.log("found one!!!!");
return sEntry[0] + '=' + 'KJHTERDY:78945'
}
}
return line
}).join('\n')
fs.writeFileSync('file_name', newData)
I've swapped the forEach for map which lets us change the array data by returning the desired value. The new array is then joined back together and written back to the file.

Related

Using document.getElementsByClassName

I coded two lines of PHP that allow me to protect an email address.
$mymail=strrev($mymail);
$mymail=str_replace("#","<b>#</b>",$mymail);
echo "<span class='spdefense'>".$mymail."</span>";
totiko#gmail.com becomes moc.liamg<b>#</b>okitot in source code
The problem is that users can no longer copy and paste e-mail addresses transformed in this way. So I want to create a javascript function that allows on a ctrl+c to:
Reverse string and remove <b> tags around # for all email adresses on a page.
No matter to reverse string and replace <b> tags. Mail adress is inside a span element with a class.
longueur=document.getElementsByClassName("spdefense");
for(var i= 0; i < longueur.length; i++)
{
machaine= document.getElementsByClassName("spdefense")[i].textContent;
machaine.split().reverse().join();
machaine.replace("<b>#</b>", "#");
}
I looked at "copy" and "clipboard" but I can't produce a valid code, to tell the truth I'm not sure if can be done...
A few things:
You want to re-use the longueur variable, as that's more efficient than grabbing all the classes twice.
You want to define it in the local block scope, not in the global one, using the const keyword.
You want to use the spread operator [...] to convert the string to an array of characters.
You want to join on an empty string .join(''), as the default for join is to use commas ,.
You want to save the result back to a variable.
You want that variable, machaine, to also be block scoped, rather than globally scoped.
You want to export the result out of the loop somehow, using an array, output, in the below example, seems appropriate.
const longueur = document.getElementsByClassName("spdefense");
const output = [];
for(var i = 0; i < longueur.length; i++)
{
const machaine = [...longueur[i].textContent].reverse().join('');
output.push(machaine.replace("<b>#</b>", "#"));
}
console.log(output);
That should work a little better... I haven't tested it, but it seems right.
As for the copy & paste, you can take a browse of the API documentation over at MDN.
The long and short of it is that you can use something like:
function setClipboard(text) {
const type = "text/plain";
const blob = new Blob([text], { type });
const data = [new ClipboardItem({ [type]: blob })];
navigator.clipboard.write(data).then(
function () {
/* success */
},
function () {
/* failure */
}
);
}
On a button click, which will add whatever text is, to the users system clipboard. There are permission considerations to take in to account, but chrome has it enabled by default (IIRC).
You can write to the clipboard via:
navigator.clipboard.writeText()
Consequently, when a user copies an email address, you can:
grab the obfuscated contents of the <span> which registered the copy event
deobfuscated those contents
write the deobfuscated contents to navigator.clipboard
Working Example:
const obfuscatedEmail = document.getElementsByClassName('obfuscated-email')[0];
obfuscatedEmail.addEventListener('copy', (e) => {
e.preventDefault();
let deobfuscatedEmail = e.target.textContent.split('').reverse().join('');
navigator.clipboard.writeText(deobfuscatedEmail);
});
textarea {
display: block;
width: 300px;
height: 60px;
margin-top: 12px;
resize: none;
}
<h2>Copy and Paste the obfuscated email below:</h2>
<span class="obfuscated-email">moc.liamg<b>#</b>okitot</span>
<textarea></textarea>

Looping through a text file in React or JS

I'm getting a text file as API response from here https://api.pwnedpasswords.com/range/D0597 that looks like this
007F24D71AC210875C58951F5D99ACC71D2:3
0097880A0B749B59A5F7FD0D943A133ADE1:4
00CAEC74DE2FA10428E6D3FAD065D53B865:4
00F8C45A33243D0A4FD293DC70130E82E00:1
024556F4CB4A1DA178A6EC4E43ECED22467:1
030BA417A72B878EC629BD585705D306260:1
03664676C5A123BE6927DB6BAC5F5427468:1
0491953CF08D183806C28DB827835D27348:1
04BA7B823BBB772A8172F94A757AAF59A39:2
04D3C208B89E12C60AB12900690E86C13DA:1
06856BA40BCB6BCE13C40F271487F347BA5:1
071E3D06232DEA85E297102F6037164C033:5
and I need to loop through and check if the value of an input is included in the list of first item. If present I need to show the second value after ":".
I was trying to use split() for new line and ":" and iterate but kind of got lost.
// data is your text file
var foo = data.split("\n"),
bar = "your input";
Object.keys(foo).forEach(function(key) {
if (foo[key].split(":")[0] === bar) {
console.log(foo[key].split(":")[1]);
}
});

Add an object to JSON

I have a settings.json file that contains following data (where 123456789 is a distinct user id):
{
"123456789":
{"button_mode":true}
}
So what I need to do is push a similar id: {button_mode: value} object to this JSON file in case there's no entry for current user's id. I tried to use lcSettings.push() but obviously it did not work since I have an object, not an array. When I put square brackets instead of curly ones to make it an array, my code doesn't do anything at all.
Here's a snippet of it (Node.js):
var lcSettings = JSON.parse(fs.readFileSync('./settings.json', 'utf8'));
var currentUser = id;
if (lcSettings.hasOwnProperty(currentUser)) {
// in case settings.json contains current user's id check for button_mode state
if (lcSettings[currentUser].button_mode == true) {
// if button_mode is on
} else
if (lcSettings[currentUser].button_mode == false) {
// if button_mode is off
}
} else {
// in case there's no entry for current user's id
// here's where I need to push the object for new user.
}
fs.writeFileSync('./settings.json', JSON.stringify(lcSettings))
Does anybody have ideas on how it can be implemented? Any help appreciated.
You can use bracket notation to add a dynamic property to an object:
lcSettings[id] = { button_mode: false };
You may also want to verify that settings.json is not empty otherwise the JSON.parse() will fail. In this case, you would want to initialize lcSettings to an empty object (lcSettings = {}) so the above will work.
To 'push' elements to an object you simply define them, as in
object['123456789'] = { button_mode: true };

how to print a javascript object's elements

i am new to javascript and i currently have an object printed to console when i use the following code:
clickEvents: {
click:function(target) {
console.log(target);
}
}
when i view console i can see the following object:
i am banging my head against a wall to write code that takes the object and prints it to a div using the .append() method. i am extermely new to working with javascript objects, and would appreciate any help trying to tease out an object and/or print the object data.
is events the object name? would i tease out the eventDate using something like events->eventDate?
I've made this over ~15 minutes so it's imperfect; there are types and edge cases surely unaccounted for and the design of the function could be better - not to mention that performing all of this as a giant string and then setting that as HTML is likely bad practice (I'm used to React now, ha!). Regardless, this will iterate over any array or object you pass to it and print it all in a big <ul> recursively.
const targetEl = document.querySelector('.js-target')
if (!targetEl) return
// Small helper functions
const isObj = data => typeof data === 'object' && !Array.isArray(data) && data !== null
const isArr = data => Array.isArray(data)
const dataToHTML = (data, noNode = false) => {
if (isObj(data)) {
const accumulator = Object.entries(data).reduce((acc, set) => acc + `<li><strong>${set[0]}</strong>: ${dataToHTML(set[1], true)}</li>`, '')
return `<ul>${accumulator}</ul>`
}
else if (isArr(data)) {
const accumulator = data.reduce((acc, item) => acc + dataToHTML(item), '')
return `<ul>${accumulator}</ul>`
}
else return noNode ? data : `<li>${data}</li>`
}
const logHTML = dataToHTML(exampleData)
targetEl.innerHTML = logHTML
Assuming that your data/variable is named exampleData.
Any questions pop them in the comments :-)
I'm not sure if you have a div that you want to append to already, but you would do something like this ->
document.getElementById("toBeAppendedTo").innerHTML = target.events[0].eventDate; where toBeAppendedTo is the id of the div you're trying to add this text to.
append() is a jquery function, not a javascript function.
That won't have any formatting and will just be the string value 07-28-2017 in a div.

Selecting the exact match from xml using jquery

Below is the sample XML.
<segment>
<departure-date-time>2015-01-31T10:40:00</departure-date-time>
<arrival-date-time>2015-01-31T14:00:00</arrival-date-time>
<data-details>
<stop-details>
<arrival-date-time>2015-01-31T12:25:00</arrival-date-time>
<departure-date-time>2015-01-31T13:00:00</departure-date-time>
<layover-duration>2100</layover-duration>
</stop-details>
</data-details>
</segment>
I want the value from the sample XML for that one i wrote
$('segment', this).each(function(index, element) {
var arr_tym =$(element).find('arrival-date-time').text();
var dst_tym =$(element).find('departure-date-time').text();
});
If i use like this i am getting the result, but it is taking the value of
also and printing as 2015-01-31T14:00:002015-01-31T12:25:00
actual output should be 2015-01-31T14:00:00. . I want all these values .
<departure-date-time>2015-01-31T10:40:00</departure-date-time>
<arrival-date-time>2015-01-31T14:00:00</arrival-date-time>
I dont want values inside
Then what about using this in the loop ?
var dep = $(element).find('departure-date-time')[0].innerHTML;
var arr = $(element).find('arrival-date-time')[0].innerHTML;
Besides the fact that you're using jQuery on XML data, replacing $('segment', this) by $('segment > departure-date-time', this) should do the trick here, and simplify the second part, as it will directly select the only first departure-date-time in your segment :
$('segment > departure-date-time, segment > arrival-date-time', this).each(function(index, element) {
var text=$(element).text();
console.log(text);
});

Categories

Resources