write file with "\n" with node.js - javascript

Im working with a lot of datas which i turned into arrays , for simplicity lets assume i have array that looks like this
["dataone:dataone","datatwo:datatwo","datathree:datathree"]
im writting output to the file using fs.writeFile
but the output is always in the same row e.g dataone:dataone","datatwo:datatwo","datathree:datathree
i would like to output to be like with "\n" e.g
dataone:dataone
datatwo:datatwo
datathree:datathree
is it possible to make output in file look like this? im writting in into .txt file

Join the data with line breaks before writing to file
var os = require('os');
var brk = os.platform().substring(0,3).toLowerCasee() === 'win'
? '\r\n' : '\n';
var data = ["dataone:dataone","datatwo:datatwo","datathree:datathree"]
fs.writeFile(filename, data.join(brk), {encoding : 'utf8'}, function (e) {
// etc
});

You can join your array with \n before writing it to the file:
var arr = ["dataone:dataone","datatwo:datatwo","datathree:datathree"]
var arr2 = arr.join('\n');

Related

How do I split a path file string in different parts and then print it out with JavaScript?

I am working on a project for fun using IndexOf, splitting... and I am trying to get my code to print out the content before the ":" and after for each line. Instead I'm getting issues combining 2 pieces of code by going to each number of lines and splitting them. I’m looking for maybe a for/while loop so it grabs each part for each line and assigns it to the var (origin,color). (I eventually want to call var - origin,color in my later script.
I have tried looking around on guides but haven't found something to cement the 2 ideas together. Might be easy but Im just missing it...
EDIT: [From CODE 1]-
console.log(lines);
Gives:
[ 'Level1:Blue', 'Level2:Red', 'Level3:Green' ]
CODE 1
var fs = require('fs');
var path = 'file.txt';
var text = fs.readFileSync(path).toString();
var lines = text.split('\n');
var newlines_count = lines.length;
var i=0; //looping through the lines
var count=1; //counts how many
var linechange=1;
for (; i < newlines_count; )
{
linechange = lines[i];
console.log(lines);
console.log(count);
i++;
//counts how many lines in the string
}
CODE 2
var str = "Level1:Blue";
var long=str.length;
var place=str.indexOf(":")
//console.log(place)
var origin=str.slice(0,place);
var color=str.slice(place+1,long);
console.log(origin);
console.log(color);
//splits the content before and after the ":"
//Code 2 Doesn't have the long string from Code 1 so the variable "long" wont really work
The info in the .txt file is(can be anything w/ ":"):
Level1:Blue
Level2:Red
Level3:Green
...(keeps going as I add more)
What I'm trying to get printed out:
Level1
Blue
Level2
Red
Level3
Green
You could split the string and join it with some linefeeds and make your output.
function splitPrint(string) {
var parts = string.split(':');
console.log(parts.join('\n\n'));
}
splitPrint('Level1:Blue');
Output line for line
function splitPrint(string) {
var parts = string.split(':');
parts.forEach(part => console.log(part));
}
splitPrint('Level1:Blue');

in javascript how to call powershell script

I have a powershell script and I run on powershell like :
.\download-packages-license.ps1
But I want to call the javascript file before these lines.
var json =fs.readFileSync('../../dev/licenses/AllLicenses.json', 'utf8');
var options = {compact: true, ignoreComment: true, spaces: 4};
var result = convert.json2xml(json, options);
I could not anything in stackoverflow except : How to run a powershell script from javascript?
So pls help thanks
I think this will work for you -
var spawn = require("child_process").spawn;
spawn("powershell.exe",[".\download-packages-license.ps1"]);
You can work with : Node-Powershell
Code Snippet :
const Shell = require('node-powershell');
const ps = new Shell({
executionPolicy: 'Bypass',
noProfile: true
});
ps.addCommand('echo node-powershell');
ps.invoke()
.then(output => {
console.log(output);
})
.catch(err => {
console.log(err);
});
JScript
Simple way.
Works great. Suitable for simple operations, but loses some data when receiving line feeds as a single \n instead of the expected \r\n. Split by \r\n misinterprets the array which leads to the need to reformat the array of strings. Basically, I just wrote this, so there may be other problems.
var codepage='windows-1251';/*US-Europe-1252 and Js file in that codepage*/
var toPStext='Hello.\nПроверка русских буковок.';
var shell=new ActiveXObject('WScript.Shell');
var std=shell.Exec("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy Bypass -command \
$OutputEncoding = [Console]::outputEncoding = [System.Text.Encoding]::GetEncoding('"+codepage+"'); \
Write-Output '"+toPStext+"'");
var output = std.StdOut.ReadAll().split('\r\n');// split('\n') - leads to the loss of some data
if (output.length>0){WScript.echo(output)}
//var x=WScript.StdIn.ReadLine();
Line by line.
Unfortunately, powershell does not accept external data as sequences of lines, unlike cmd.exe with /q /k options, which simplifies this code, but will turn around problems with multiline output code. Of course, if necessary, you can transfer the code as a base64 string to powershell
var codepage='windows-1251';/*US-Europe-1252 and Js file in that codepage*/
var toPStext='Hello.\nПроверка русских буковок.';
var shell=new ActiveXObject('WScript.Shell');
var output=[],errors=[],WshRunning=0,WshFinished=1,WshFailed=2,i=0,tryCount=0;
var std=shell.Exec("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy Bypass -command \
$OutputEncoding = [Console]::outputEncoding = [System.Text.Encoding]::GetEncoding('"+codepage+"'); \
Write-Output '"+toPStext+"'");
do{
if (std.Status==WshFailed){
errors.push('String '+i+' data read error: \n '+std.StdErr.ReadLine());
tryCount++
}
else if(std.Status==WshRunning){
output.push(std.StdOut.ReadLine());
tryCount=0;
WScript.Echo('Running ...')
}
else if(std.Status==WshFinished){
var last=std.StdOut.ReadLine();
if(last.length>0){output.push(last)};last=undefined;
tryCount=21;
WScript.Echo('Finished ...')
}i++;
}while(tryCount<21);
if (output.length>0){WScript.echo(output)}
if (errors.length>0){WScript.echo(errors)}
var x=WScript.StdIn.ReadLine();

Javascript Web API JSON Parsing Format issue

Hi i have an issue with a few lines of code in JS and formatting my JSON data. Basically in my DB i have a field that is set to nchar(10) but some of the data in the fields are for example only 8 characters long.
The problem i have is when my JS generates a link from JSON data it attaches Spaces to the Data to compensate the (10) characters. For example clicking a link generated from the JS Would generate a link for me like this http://....api/Repo/rep10016
In my JSON it passes in this data
rep10016
But my JS is grabbing this data for the link adding spaces up to 10 as it is a nchar(10) like this.
repoCode = "rep10016 "
But i only want
repoCode = "rep10016"
My JS Code
function displayRepos(repo) {
var table = document.getElementByrCode("rList");
table.innerHTML = "";
for (var i = 0; i < arr.length; i++)
{
var rCode = arr[i].repoCode;
cell2.innerHTML = "<a href='#'rCode='" + rCode + "' " + " >Repo List</a>";
document.getElementByrCode(rCode).onclick = getRepo;
}
function getRepo(rep)
{
var repoUrl = genUrl+rep.target.rCode+"?code="+rep.target.rCode;
......
}
The repoUrl variable is generating a link like this
"http://....api/Repo/rep10016 ?code=rep10016 /"
How can i get my code to only take the actual data and not format it to the nchar(10) format that is in my db??
repoCode.trim() will do the trick.
I would use string.trim();
var orig = 'foo ';
console.log(orig.trim()); // 'foo'

Replace array-mapped variables with the actual variable name/string?

I am trying to edit a Greasemonkey/jQuery script. I can't post the link here.
The code is obfuscated and compressed with minify.
It starts like this:
var _0x21e9 = ["\x67\x65\x74\x4D\x6F\x6E\x74\x68", "\x67\x65\x74\x55\x54\x43\x44\x61\x74\x65", ...
After "decoding" it, I got this:
var _0x21e9=["getMonth","getUTCDate","getFullYear", ...
It is a huge list (500+ ). Then, it has some variables like this:
month = date[_0x21e9[0]](), day = date[_0x21e9[1]](), ...
_0x21e9[0] is getMonth, _0x21e9[1] is getUTCDate, etc.
Is it possible to replace the square brackets with the actual variable name? How?
I have little knowledge in javascript/jQuery and can not "read" the code the way it is right now.
I just want to use some functions from this huge script and remove the others I do not need.
Update: I tried using jsbeautifier.org as suggested here and in the duplicated question but nothing changed, except the "indent".
It did not replace the array variables with the decoded names.
For example:
jsbeautifier still gives: month = date[_0x21e9[0]]().
But I need: month = date["getMonth"]().
None of the online deobfuscators seem to do this, How can I?
Is there a way for me to share the code with someone, at least part of it? I read I can not post pastebin, or similar here. I can not post it the full code here.
Here is another part of the code:
$(_0x21e9[8] + vid)[_0x21e9[18]]();
[8] is "." and [18] is "remove". Manually replacing it gives a strange result.
I haven't seen any online deobfuscator that does this yet, but the principle is simple.
Construct a text filter that parses the "key" array and then replaces each instance that that array is referenced, with the appropriate array value.
For example, suppose you have a file, evil.js that looks like this (AFTER you have run it though jsbeautifier.org with the Detect packers and obfuscators? and the Unescape printable chars... options set):
var _0xf17f = ["(", ")", 'div', "createElement", "id", "log", "console"];
var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);
var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);
var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];
window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);
In that case, the "key" variable would be _0xf17f and the "key" array would be ["(", ")", ...].
The filter process would look like this:
Extract the key name using text processing on the js file. Result: _0xf17f
Extract the string src of the key array. Result:
keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
In javascript, we can then use .replace() to parse the rest of the JS src. Like so:
var keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
var restOfSrc = "var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);\n"
+ "var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);\n"
+ "var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];\n"
+ "window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);\n"
;
var keyArray = eval (keyArrayStr);
//-- Note that `_0xf17f` is the key name we already determined.
var keyRegExp = /_0xf17f\s*\[\s*(\d+)\s*\]/g;
var deObsTxt = restOfSrc.replace (keyRegExp, function (matchStr, p1Str) {
return '"' + keyArray[ parseInt(p1Str, 10) ] + '"';
} );
console.log (deObsTxt);
if you run that code, you get:
var _0x41dcx3 = eval("(" + '{id: 3}' + ")");
var _0x41dcx4 = document["createElement"]("div");
var _0x41dcx5 = _0x41dcx3["id"];
window["console"]["log"](_0x41dcx5);
-- which is a bit easier to read/understand.
I've also created an online page that takes JS source and does all 3 remapping steps in a slightly more automated and robust manner. You can see it at:
jsbin.com/hazevo
(Note that that tool expects the source to start with the "key" variable declaration, like your code samples do)
#Brock Adams solution is brilliant, but there is a small bug: it doesn't take into account simple quoted vars.
Example:
var _0xbd34 = ["hello ", '"my" world'];
(function($) {
alert(_0xbd34[0] + _0xbd34[1])
});
If you try to decipher this example, it will result on this:
alert("hello " + ""my" world")
To resolve this, just edit the replacedSrc.replace into #Brock code:
replacedSrc = replacedSrc.replace (nameRegex, function (matchStr, p1Str) {
var quote = keyArry[parseInt (p1Str, 10)].indexOf('"')==-1? '"' : "'";
return quote + keyArry[ parseInt (p1Str, 10) ] + quote;
} );
Here you have a patched version.
for (var i = 0; i < _0x21e9.length; i++) {
var funcName = _0x21e9[i];
_0x21e9[funcName] = funcName;
}
this will add all the function names as keys to the array. allowing you to do
date[_0x21e9["getMonth"]]()

Repeat a function in javascript for "n" times to download text in parts

I would like to download text in parts and add it to a file "foobar" by repeating the download and write function from "data1" to "datan" where n is the last piece of the text.
This needs to be done as the text file is too big to be written directly into "foobar".
My current solution (snippet) is:
var data1 = "AAAAA";
var data2 = "BBBBB";
....
path += '/foobar';
....
downloadfunction(['echo "'+data1+'" >> '+path]);
downloadfunction(['echo "'+data2+'" >> '+path]);
The code works, but my main issue is with the last two lines. Is there a way to make the code more elegant by repeating "downloadfunction" from "data1" to datan"? "n" is a known, but large, number.
Put the data in an array, then you can loop and modify your function to take data and path as arguments:
var data = ['AAAAA', 'BBBBB', 'CCCCC'];
function download(data, path){
save("echo " + data + " >> " + path);
}
...
path += '/foobar';
...
data.forEach(function(d){
download(d, path);
});

Categories

Resources