how to save file in json with javascript - javascript

I write this code for saving data in json in javascript and the error is:
Uncaught TypeError: file.open is not a function
var txtFile = "./tmp/test.txt";
var file = new File([""], txtFile);
var str = JSON.stringify("string");
file.open();
file.write(str);
file.close();
What is the problem?

Take a look at this, maybe you can use it or see how it's made:
https://github.com/eligrey/FileSaver.js

Related

Process a local CSV file with native JavaScript

I am new to this stuff.
I'm trying to build a website about finance.
I have written a scrypt in python to get shares data from an API, created my own market index and exported the datas of my index in a CSV file. It's important because, I need to create an historic and observe its evolution (the script will run automatically in a VM to add data as it goes). No problem at this stage.
Now, my purpose is to read and treat my CSV file in a JS script to stock the datas into an array (graphJS use array to display a graph and that's what I want to use).
I only found solutions that use an <input> HTML (user import a CSV on a website, I do not need that) or JSQuery (I have never been able to use it)
I'm looking for a native JavaScript solution. For the beginning, I am just looking to display datas from my CSV in console.log(). And with a "for" loop, use ".push" to iterate the datas into an array. But I will do this after I successfully displayed my file in the console.
My code does not work, can someone help me ?
const csvLocalFile = "file.csv";
const csv = csvLocalFile.files[0];
const reader = new FileReader();
reader.readAsText(csv);
TypeError: Cannot read properties of undefined (reading '0')
The Issue Is That You Are Trying To Access The File Contents From A Variable Of Type String.
What Your Code Does Is Try To Reference An Element Inside This String Like A Map Which doesn't Exist. Giving The Error.
Also In The Code It Only Creates A New Variable whose contents are file.csv and doesn't actually store the file.
To Actually Get The Contents Of Your CSV:
var filecontent
// https://stackoverflow.com/a/29176118
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var text = reader.result;
filecontent = text.replace("","")
};
reader.readAsText(input.files[0]);
};
And In Your HTML
<input type="file"onchange="openFile(event)">
Your CSV Contents Will Be Stored Inside the Variable filecontent
EDIT: Non File Upload Types
let obj = await (await fetch('file.csv')).text();
This Contains Your CSV.

How to read and show xslx file in javascript

I'm trying to read a xlsx file in html using javaScript but it seems my code is not so right as it should be.
I'm using this code:
<script>
function openRead(){
var excel = activeXObject("Excel.Application");
excel.visible = false;
var file = exel.workbooks.open("C:\Users\Utilizador\Desktop\teste.xlsx").activeSheet.cell(1,1).value;
var div = document.getElementById("div1").text;
div = file;
}
</script>
Getting the following error
activeXObject is not defined
I hope you guys can point me to the right direction!
ActiveXObject is available only on IE browser. So every other useragent will throw an error
https://stackoverflow.com/a/11101655/1172872
You can try existing libraries... (or see how they implemented it)
http://sheetjs.com/ (https://github.com/SheetJS/js-xlsx)
http://oss.sheetjs.com/js-xls/

Difference between Javascript & C# Image File array

In C#, I read an image file into a base64 encoded string using:
var img = Image.FromFile(#"C:\xxx.jpg");
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
var arr = ms.ToArray();
var b64 = Convert.ToBase64String(arr);
In javascript, I do this:
var f = document.getElementById('file').files[0], //C:\xxx.jpg
r = new FileReader();
r.onloadend = function (e) {
console.log(btoa(e.target.result));
}
r.readAsBinaryString(f);
I'm getting different results.
Ultimately, I'm trying to read it in Javascript, POST that to an API, save in a database, and then retrieve & use later. If I use the C# code above, I can store the file and retrieve/display it fine. If I try the Javascript option, I don't get a valid image. So I'm trying to work out why they're different / where the problem is. Any pointers?

Can't parse JSON file - Unexpected token

I've created json file using Visual studio:
{
"test": "asd"
}
Using this code to read it:
var test = fs.readFileSync('./files/test.json')
var obj = JSON.parse(test);
which results in error: Unexpected token  in JSON at position 0
When I try to read package.json, it is read correctly. Does anyone know why I can't read my file?
You have 2 options
add encoding option
var test = fs.readFileSync('./files/test.json', {encoding: 'utf8'})
var obj = JSON.parse(test);
If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
require json
var obj = require('./files/test.json');
As of node v0.5.x yes you can require your JSON just as you would require a js file.
I hope this code help u
$.getJSON("/files/test.json", function(json) {
alert(json['test'])
//if massage show 'object object' then firs purse
//json=JSON.parse(json) //alert(json['test']) });
Solution of the problem is opening file in notepad++ and saving it without BOM. Looks like json created via visual studio adds BOM
It looks like this is not properly formatted JSON. They modifying it like this.
var myObject = {
'test': 'asd'
};
and then you parse would be....
var obj = JSON.parse(myObject);

write bytestream to a activex object in javascript

I am trying to create a file on the local machine which captures the var file in javascript.
<script>
function button_click()
{
var file = GetFile('Getdoc'.aspx');
WriteToFile();
}
function WriteToFile() {
var fso, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
s = fso.CreateTextFile("C:\\Test\\Logfile.txt");
s.Write(file1);
s.Close();
}
</script>
Here we get a httpresponse stream which contains data in bytes into var file.
If I could find some help on this would be appreciated.
Thank you.
If I understand you correctly, you are encountering a problem when you are trying to write a file using ActiveXObject on IE? There is two things wrong with your script.
var file = GetFile('Getdoc'.aspx'); should be var file = GetFile('Getdoc.aspx');
You do not have file1 defined, so it is writing nothing to the file.
You need to keep in mind that most versions of IE have this functionality disabled due to the huge security risk that this poses.

Categories