Inserting new lines to be read in a .txt file - javascript

I have the following code for creating a .txt file in javascript:
var text_block = '';
text_block += "Variable 1:"+var1+"\r\n";
text_block += "Variable 2:"+var2+"\r\n";
text_block += "Variable 3:"+var3;
var zip = new JSZip();
zip.file("variables.txt", text_block);
It's going into a zip file because it will ultimately be packaged with other files. When I run this script, it's creating the text file, but there are no new lines/carriage returns when opened in notepad. They do show when opened with wordpad, but I can't assume people are going to use that by default for a .txt file. What can I do to show line breaks in notepad?

Looking at the source of JSZip, in the file jszip.js of the download package on their website, I noticed this line of code (line 661-662):
utf8encode : function (string) {
string = string.replace(/\r\n/g,"\n");
So it seems like that's your problem. Perhaps you could try commenting out line 662, I don't know why it's there, it may well break something else. It seems they copied the code from here, as per the url in the source.

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.

Cannot write to file in Titanium

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.

Javascript to get .pdf file from partial match

Complete and utter javascript newbie here with a problem fetching .pdf files from a web server based on a partial match. I have made a program that outputs data to a webserver, and one of the components is a folder of .pdf files. I want to be able to click on a link that will pull up the corresponding .pdf file based on a value in the data table that's generated (I'm using slickgrid for this). Each of the .pdf files contains the value that's in the data table and serves as good query to the .pdf folder, and I've been successful at getting the .pdfs I want with the following code:
var value = grid.getData().getItem(row)['data'];
var locpath = window.location.pathname.substring(0,window.location.pathname.lastIndexOf('/'));
var plotsFolder = window.location.protocol + "//" + window.location.host + locpath + "/CovPlots/";
var href = plotsFolder + value + ".pdf";
return "<a href='" + href + "'>" + value + "</a>";
The catch here is that sometimes the .pdf file that's generated is a concatenation of two or more (I've seen up to 4 so far) of the 'data' strings, separated by '_' as a delimiter for reasons not worth getting into. So, if the .pdf file is 'somestring.pdf', I can get it without problem. However, if the .pdf file is 'somestring_anotherstring.pdf', I can't figure out how to get that .pdf file if I have either 'somestring' or 'anotherstring' as the value of 'data'.
I've tried a ton of different things to get some kind of lookup that I can use to pull down the correct file based on a partial match. The latest attempt is with the FilenameFilter object in javascript, but without any knowledge of javascript, I'm having a hard time to get it working. I tried to create a new function that I could call as a lookup for the .pdf URL:
function lookup() {
File directory = new File(plotsFolder);
String[] myFiles = directory.list(new FilenameFilter() {
public boolean accept(File directory, String fileName) {
return fileName.match(value);
}
});
}
That only seems to thrown an error. Can anyone point me in the right direction to be able to download the correct .pdf file based on a partial match? I also tried to see if there was a jquery way to do it, but couldn't seem to find something that works. Thanks in advance!
Without support from the server, JavaScript cannot find a file from a partial filename. What you can do, however, is have a little script on the server that does the partial-filename-matching for JavaScript, and then JavaScript can ask the server to do the match, and then when it gets the match back, it can use that filename.
If you don't mind loading a whole index of all the PDFs at once, you could use this little Python script to generate an index in a nice, JavaScript-friendly JSON format:
#!/usr/bin/env python
# Create an index of a bunch of PDF files.
# Usage: python make_index.py directory_with_pdf_files
import os
import sys
import json
def index(directory):
index = {}
for filename in os.listdir(directory):
base, ext = os.path.splitext(filename)
if ext.lower() != '.pdf':
continue
for keyword in base.split('_'):
index[keyword] = filename
with open(os.path.join(directory, 'index.json'), 'w') as f:
f.write(json.dumps(index))
if __name__ == '__main__':
index(sys.argv[1])
Then you can just load index.json with jQuery or what-have-you. When you need to find a particular PDF's filename, you can do something like this (assuming the object loaded from index.json is in the indexOfPDFs variable):
var href = plotsFolder + indexOfPDFs[value];

save result to txt file on company shared folder

this is my problem i cant save my results to driver x that is company shared folder and i have permission to write for some reason , but i can save on driver c.
the messege show
Webpage error details
Message: Automation server can't create object Line: 93 Char: 1 Code:
0 URI:
file:///X:/OmrilDocs/Omrix%20Public/All%20Omrix%20Public/Training/index.html
notic : i can use only javascript , no server side language is allowd :(
this is the code i use
alert(answerText);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("X:\OmrilDocs\Omrix Public\All Omrix Public\Training\text.txt", true);
s.WriteLine(answerText);
s.Close();
im using ie8 on xp 2
You need to replace \ with \\.
It should look like:-
var s = fso.CreateTextFile("X:\\OmrilDocs\\Omrix Public\\All Omrix Public\\Training\\text.txt", true);
While it is running, it gives a popup window which you need to allow to create the file.
Screenshot look like:-
Eventhought you've loaded index.html from server, the code is executed in the work station.
You've written the path literally in your function. However, FSO tries to find the target from the work station only, and it is not capable to follow a path associated to some drive letter. (In other work stations that same path might be associated to a different letter.)
So, you need to to use the real name (or IP) of that server:
fso.CreateTextFile("//YOUR_SERVER_NAME/OmrilDocs...
Also the saving folder have to exist. When using true-argument in CreateTextFile only a new file is created to the provided path, new folders are not. Hence if there is a misstypo in the pathname, function will fail.

Categories