Cannot write to file in Titanium - javascript

I am having trouble writing to a file in Titanium Studio.
specifically .json file. Code is compiled through and no exception was thrown.
Here is my relevant section of code, I parse the file to var first before adding element and stringify it to be written back.
Reading works perfectly, so is adding element, it's the writing process that has issues
var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'data.json');
var jsontext = file.read().toString();
var jsondoc = JSON.parse(jsontext);
jsondoc['feedlist'].push({
"picloc":imagename,
"title":titlef.value,
"desc1":descf1.value,
"desc2":descf2.value,
"desc3":descf3.value
});
jsontext = JSON.stringify(jsondoc);
file.write(jsontext); // write(data,[append])
Note: I have consulted Documentation and done some of my own search, some are suggesting that "Filestream" should be used in place of normal file along with .close(), I have yet got them working but it could be pointers the solution, if anyone knows how to get it working
Thanks in advance.
EDIT: This question is flagged for duplication, initially I deemed that was 2 separate issues, one was about merely writing text to a file. Another is parsing event.media (picture) into a file.

I got it working now, The issue was that I was trying to write to file in read-only directory
Ti.Filesystem.resourcesDirectory: A read-only directory where your application resources are located
Ti.Filesystem.applicationDataDirectory: A read/write directory accessible by your app. Place your application-specific files in this directory.
The contents of this directory persist
until you remove the files or until the user uninstalls the application
Here is my code, directory is modified
var sesfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'data2.json');
var jsontext = sesfile.read().toString();
var jsondoc = JSON.parse(jsontext);
jsondoc['feedlist'].push({
"picloc":imagename,
"title":titlef.value,
"desc1":descf1.value,
"desc2":descf2.value,
"desc3":descf3.value
});
jsontext = JSON.stringify(jsondoc);
sesfile.write(jsontext,false);
If you are unable to locate data directory and simply want to load the file from there.
(In my case it does not exist in project nor will be created with Webpreview compilings)
You can do bootstrap-ish type instruction like this first
var rdfile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'data.json');
var sesfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'data2.json');
var jsontext = rdfile.read().toString();
var jsondoc = JSON.parse(jsontext);
sesfile.write(jsontext);
hope it helps whomever makes amateur mistake like I did.

Related

Unable to update a file

I have a file which I am updating using fs and then creating zip in other location. When I check, file update is working fine, but in zip updated contents are not there. Can you tell me what I am doing wrong here. Here is my code.
const content = "new content";
const outputFile = `${unzipDir}/output.docx`
const zip = new AdmZip(outputFile);
fs.writeFileSync(`${unzipDir}/word/document.xml`,content); //content updated successfully in this path.
zip.addLocalFolder(`${unzipDir}/_rels/`);
zip.addLocalFolder(`${unzipDir}/customXml/`);
zip.addLocalFolder(`${unzipDir}/docProps/`);
zip.addLocalFolder(`${unzipDir}/word/`);
zip.addLocalFile(`${unzipDir}/[Content_Types].xml`);
zip.writeZip(outputFile);//old content is showing when extracting zip
Finally I got the solution. When we try to add local folders like I have done in above code, it not add folders and instead add all files containing those folders to root. So in that case file from original location was not replaced and I got old contents. So instead of adding all folders one-by-one, I have added entire folder structure at once and it works for me.
//zip.addLocalFolder(`${unzipDir}/_rels/`);
//zip.addLocalFolder(`${unzipDir}/customXml/`);
//zip.addLocalFolder(`${unzipDir}/docProps/`);
//zip.addLocalFolder(`${unzipDir}/word/`);
//commented above lines and added below line
zip.addLocalFolder(`${unzipDir}/`);
Hope this will help others also.

Javascript, Typescript, Angular 5 - Open and read file

I am working with Angular 5, I have an application in which I need to read an AMP HTML file as text. This file is contained in a component and should only be accessed from this component.
I would like to be able to open the file in read-only by giving its name.
I'm actually searching for something like this:
let file = open('amp.html');
Is it possible? If not how can I do to achieve this?
If you're writing browserside JS
You can't just simply read a file. The JS is running on your browser, and you need to think about where you're getting that file from.
If the file is on a server, you need to fetch that file from the server first by making a request for it.
If you're reading a file on the user's computer, you're gonna be using the File API on the browser to allow the user to select that file.
If you're writing backend JS
Assuming you're using NodeJS, you can conduct file operations like you would with other programming languages. Check out the fs module
If i understand you correct, you can read it as text like this:
function readFile(file){
var raw = new XMLHttpRequest(); // create a request
raw.open("GET", file, false); // open file
raw.onreadystatechange = function (){ // file is ready to read
if(raw.readyState === 4){
if(raw.status === 200 || raw.status == 0){
var allText = raw.responseText;
alert(allText); // can be also console.logged, of course.
}
}
}
raw.send(null); // return control
}
usage:
readFile('link.html')
I solved this issue thankfully to this question.

Illustrator JS Script Run without app.activeDocument

I have been using Illustrators API to create a script that is able to export .ai files swatches into a JSON format.
This however is all by having to open the Illustrator file and click
File > Scripts > Run My Script.
This is something that is very tedious and was wondering if there was a way in order to take the the files location (file path) and just execute the program using something like Node which will just use my already existing code and my AI file.
Currently I have something that looks along the lines of:
var Exporter = function() {
this.swatchGroup = 'ClientColours';
this.myApp = app.activeDocument;
this.chosenSwatchGroup();
this.writeFile(); };
What I am thinking is there not a way to instead of having this.myApp = app.activeDocument; to rather have something like this.myApp = Path(../my location);?
I have been making us of this documentation Jongware and Adobe Documentation just cant seem to find the answer I am looking for in order to get closer to this sort of automation.
EDIT
Did some digging and found the application documentation and there is a 'path' property just not sure on its implementation. Documentation
Yes, you can do this by providing path. But you have to open that file and that file will be your activeDocument. For eg :
var file = File("../your location");
app.open(file);
this.myApp = app.activeDocument;
By this, the file at your location will get open in Illustrator and will be activeDocument.

CRUD Excelsheets using Javascript for creation Automation Framework with Protractor

I have worked with Selenium in creating framework for Quality Automation Testing. This was having separate files for Test Cases(Excelsheets file format), Object Map (XML format), ec.
My company has started using AngularJS and I am thinking of creating a similar Quality Automation framework using Protractor.
Since, Protractor is based on Javascript, I am wondering
1. If I can read an excel file using Javascript ?
2. Whats the best way to do so ?
I read few online forums, blogs asking is it server side or client side; suggesting various things like converting it to XML, JSON, blah blah. Also, I found JS XLS and JS XLSX. Its all confusing and wanted insights into this with clear perspective of its use with Protractor / Javascript.
Thanks for your help, suggestions and advices.
Hi please do it like below to read xlsx file via javascript for automating angular based websites using protractor (for more info plz visit https://www.npmjs.com/package/xlsx)
This is my first js file with name excelReader.js
var excelReader = function(){
if(typeof require !== 'undefined')XLSX = require("../path/xlsx"); // path for xlxs directory that you have downloaded via npm
var workbook = XLSX.readFile("C:\\Users\\path\\Desktop\\nameofexcel.xlsx");
var first_sheet_name = workbook.SheetNames[0];
this.Reader = function(cellValue){
var address_of_cell = cellValue;
var worksheet = workbook.Sheets[first_sheet_name];
var desired_cell = worksheet[address_of_cell];
var desired_value = desired_cell.v;
return desired_value;
};
}
module.exports = new excelReader();
and in main test you can use it like below (i have used jasmine data provider)
var DataProvider = require("../path/excelReader.js"); // call the excelReader.js file
var using = require("../path/jasmine-data-provider"); // calling jasmine data provoider if u want u can leave it.
describe("you text suite",function(){
var dataProvider = {
"Case 1 : Valid username and Invalid password" : {UN : DataProvider.Reader("C2"),PWD : DataProvider.Reader("D2")}, // C2 and D2 are excel cell value
};
using(dataProvider, function(Parameter, description) {
xit("your spec file(login example) " + description,function(){
LoginPage.UserName(Parameter.UN); // here i have called the excel value which contains username and password
LoginPage.Password(Parameter.PWD);
LoginPage.SignIn();
});
});
});
hope this helps you in case of any query plz ask.

Javascript: how to append data to a file

how can i append data to a file using javascript?
i tried to use this code, but i got an error:
var fso = new ActiveXObject("Scripting.FileSystemOject");
var filepath = fso.GetFile("member.txt");
var fileObject = fso.OpenTextFile(filepath, 8);
file.WriteLine(id + "|" + pass);
fileObject.close();
the error is on var fso = new ActiveXObject("Scripting.FileSystemOject");, written: Error: Automation server can't create object
is there any other way to append the file using javascript or the way to fix this? thanks :)
EDIT:
i have doing what's written on this, and it still not working :/
I just realized these in your code:
var fileObject = fso.OpenTextFile(filepath, 8,true);
You'll need the true-argument, if the file does not exist, or you want to overwrite/append it.
var filepath = fso.GetFile("member.txt");// This won't work.
var filepath = "your_filePath"; // Use this instead
var fileObject = fso.OpenTextFile(filepath, 8, true);
OpenTextFile() needs a path as a string like "D:/test/file.txt". GetFile() returns an object, which you can see as a string (D:\test\file.txt), but it's not a string. Use also absolute paths, relative paths don't seem to work by my experience.
EDIT
Add the code below to the <head>-part of your html-file, then save locally as a hta (with file extension hta, not htm or html).
<hta:application
applicationName="MyApp"
id="myapp"
singleInstance="yes"
/>
Then run the hta-file. If you still getting an ActiveX-error, it's not supported by your OS. If this works, you haven't done all the security settings correct.
EDIT II
In this case it's not very usefull to get the path through ActiveX, you'll need to write it literal anyway. And I'm not supposed to do your homeworks, but this does the trick...
var filepath = new String(fso.GetFile("member.txt")).replace(/\\/g,'/');
And don't forget what I've said above about using absolute paths...
The 8 in the OpenTextFile function specify that you want to append to the file. Your problem comes from the security restriction of your browser. To make it work you'll have to lower the security level, which is not really recommended.
The error is thrown because there are security restrictions which donot allow the activex to run. change your security settings to allow the activex if your using internet explorer (which i think you are).
This might be useful http://windows.microsoft.com/en-US/windows/help/genuine/ie-activex
Cheers
EDIT: i have doing what's written on this, and it still not working :/
* try Restarting your browser
As pointed out in this comment
Javascript: how to append data to a file
the cause of the error Error: Automation server can't create object is the typo in the progid passed to ActiveXObject: Oject instead of Object:
var fso = new ActiveXObject("Scripting.FileSystemOject");
there is a missing b!

Categories