Save data to an external file - javascript

Hello, I am currently developing a website for my personal needs for which I need to be able to regularly save data in a "data.json" file, which I can then retrieve for later use.
I then remembered that I had already used the "file sync" module of NodeJs before, but this time I can't manage to use it with my project as it doesn't seem to apply to my html files...
I suspect that there are other easier solutions or that I must be using NodeJs wrong in this case.
I use the sublime text editor and I work on 2 html files linked to the same script.js and style.css file
Would you have solutions to propose to me?
Thank you, cordially,
Florent

Let's say at the backend.
const htmlTxt = `
<html>
...
</html>
`
// write the file locally
fs.writeFileSync("sampleHtml.html", htmlTxt);
// read the contents of the file
console.log(fs.readFileSync("sampleHtml.html", "utf8"));

I would use the File system module.
So on your nodeJS server, you would have to add:
const fs = require('fs');
then create your json:
let jsonElement = {
aa: 'aa',
test: 123,
};
let data = JSON.stringify(jsonElement);
And save it to file
fs.writeFileSync('json_file.json', data);
https://nodejs.org/api/fs.html

Related

Angular *.docx and *.xlsx file free tool to preview inside the application using Library like 'ngx-doc-viewer2' or Other

It's been 3 days, I am searching for a solution to display my *.docx and *.xlxs file in my angular application. I have an API which is returning the files as blob. Now, I want to use that blob to show the file. I can easily download the file using window.open(blobLink), however, my main task was to view the file. So, I searched and found ngx-doc-viewer and it does not work with the blob link as I currently found and file needed to be publicly accessible. But, my application will run in the local network. So, how can I solve this problem. Here is my *.ts and HTML code below=>
TS
getFile(fileData: File) {
this.tempBlob= null;
this.ProposalService.getFile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
},
(err: Error) => {
},
() => {
const blob = new Blob([this.tempRetFileData], { type: this.contentType });
this.docURL = window.URL.createObjectURL(blob);
}
);
}
HTML
<ngx-doc-viewer [url]="docURL" viewer="google" style="width:100%;height:50vh;"></ngx-doc-viewer>
Note: Any other free Library and solution is acceptable.
For blob type use viewer="mammoth":
<ngx-doc-viewer [url]="docURL" **viewer="mammoth"** style="width:100%;height:50vh;"></ngx-doc-viewer>
To use mammoth, also add:
npm install mammoth --save
and make sure mammoth.browser.min.js is loaded. For the angular/cli you would add the following in angular.json:
"scripts": [
"node_modules/mammoth/mammoth.browser.min.js"
]

how open transform xml file that is in my project folder in Javascript Object

I'm new to react native. I'm trying to transform an xml file into a Javascript object for parse it after. My problem is that I am not able to pass at readFile method, the path of my project folder.
I'm using react-native-fs module, in this mode:
var RNFS = require('react-native-fs'),
xml2js = require('react-native-xml2js');
parser = new xml2js.Parser()
RNFS.readFile(what path?, (err, data) ->
parser.parseString data, (err, result) ->
console.dir result
console.log 'Done.'
Someone can help me?
thanks.
P.s.
My project structure is:
Myapp
|--->App
| |--->Components
| |--->Xml
|--->Android
|--->``Ios
...
How can I reference xml folder in my code?
there are APIs in 'react-native-fs'/FS.common.js to get directory paths.for example:DocumentDirectoryPath, ExternalStorageDirectoryPath, ExternalDirectoryPath etc.
it depends on where the file is
read file in the bundle on Android. use
RNFS.readFileAssets("a/b/c.txt")
read file in the app own director on Android and iOS, use
RNFS.readFile(RNFS.DocumentDirectoryPath + "/a/b/c.txt")
read file in sdcard on Android, use
RNFS.readFile(RNFS.ExternalDirectoryPath + "/a/b/c.txt")

Use node.js to save json file

I am very new to Node server/javacsript. So I am sorry if this might be stupid
question/topic.
I intended to create a very simple solution to open JSON file, load to list, and save it back to my local disk (running node.js server).
Could you please help me out, what I am doing wrong? I am running app in browser using react.
index.js containing
var fs = require('fs');
var fileName = './test.json';
var file = require('./test.json');
alert(file.name + " " + file.age);
file.name = "Peter";
alert(file.name + " " + file.age);
fs.writeFile('./test.json', JSON.stringify(file), function (err) {
if (err) return alert(err);
console.log(JSON.stringify(file));
alert('writing to ' + fileName);
});
Before I was not even able to open JSON file. I needed to include this property into the webpack config file.
node: {
fs: 'empty'
}
Now I am able to open JSON file, change it virtually, but unable to save it.
In chrome developer tools, it prints "fs.writeFile is not a function" into console.
Thank you very much.
When you included the property in your webpack config
node: {
fs: 'empty'
}
You told webpack that the module fs should just be an empty object. You can confirm this by simply putting a console.log(fs) in your file to see it is indeed empty.
Beyond that, fs is not going to work in your browser. fs expects the node.js runtime (which includes non-JavaScript things in order to make it work), not your browser's runtime.
If you want a user to save a file, you'll have to use a browser based saving solution. You won't be able to just arbitrarily write files like that outside of something like your browser's local storage.

How to create file(.apk) from URL in Jaggery?

I have application store and applications have their url. I want to download apks from those urls to my jaggery server. Although below code(my first solution) create myApp.apk successfully, its not work properly.
First i tried to below code,
var url = "http://img.xxx.com/006/someApp.apk";
var data = get(url, {});
var file = new File("myApp.apk");
file.open("w");
file.write(data.data);
file.close();
when i print data.data value, its look like
i also tried,
var file = new File("http://img.xxx.com/006/someApp.apk");
file.saveAs("myApp.txt");
Can anyone help me?
.apk files are Android application files, and they are expected to start with PK, because they are actually zip archives!
They're not meant to be unzipped, although you can do it to see some of the application resources (but there are better ways for reverse engineering .apk files such as Apktool, if that's what you're looking for).
According to jaggery documentations, file.write is writing the String representation of the object to the file. So that's why you are getting an apk file which cannot be installed.
However you can make it work using copyURLToFile in apache commons-io java library as follows since jaggery supports java itself and all of WSO2 products have apache commons-io library in their class path.
<%
var JFileUtils = Packages.org.apache.commons.io.FileUtils;
var JUrl = Packages.java.net.URL;
var JFile = Packages.java.io.File;
var url = new JUrl("http://img.xxx.com/006/someApp.apk");
JFileUtils.copyURLToFile(url, new JFile("myApp.apk"));
print("done");
%>
Your file will be stored on $CARBON_HOME directory by default, unless you specified relative or absolute path to the file.

How to fetch file content (basically read) a local file in javascript for UIAutomation iOS

Is there a possible way to read a local file in JavaScript.
MyFolder:
db.csv
Parse.js
Trying to fetch the contents of file db.csv in Parse.js, But in vain.
Can you share some links where I can get enough knowledge how to read a file.
Running Instruments in Xcode5, with test scripts in .js file where I have to feed in some values from a .csv file.
iOS UIAutomation, apple provides an api for running a task on the target's host.
performTaskWithPathArgumentsTimeout
Using this, we can have a bash script to printout the contents of a file that we wanted to fetch in the first case.
Bash script can be as simple as this for this requirement.
#! /bin/bash
FILE_NAME="$1"
cat $FILE_NAME
Save it as for example FileReader.sh file.
And in your automation script,
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout(executablePath,[filePath,fileName], 15);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
where in,
executablePath is where the command need to be executed.
var executablePath = "/bin/sh";
filePath is the location of the created FileReader.sh file. When executed, outputs the content to standard output (in our requirement).
[give full absolute path of the file]
fileName is the actual file to fetch contents from.
[give full absolute path of the file] In my case I had a Contents.csv file, which I had to read.
and the last parameter is the timeout in seconds.
Hope this helps others, trying to fetch contents (reading files) for performing iOS UIAutomation.
References:
https://stackoverflow.com/a/19016573/344798
https://developer.apple.com/library/iOS/documentation/UIAutomation/Reference/UIAHostClassReference/UIAHost/UIAHost.html
If the file is on the same domain as the site you're in, you'd load it with Ajax. If you're using Ajax, it's be something like
$.get('db.csv', function(csvContent){
//process here
});
Just note that the path to the csv file will be relative to the web page you're in, not the JavaScript file.
If you're not using jQuery, you'd have to manually work with an XmlHttpRequest object to do your Ajax call.
And though your question doesn't (seem to) deal with it, if the file is located on a different domain, then you'd have to use either jsonP or CORS.
And, just in case this is your goal, no, you can't, in client side JavaScript open up some sort of Stream and read in a file. That would be a monstrous security vulnerability.
This is a fairly simple function in Illuminator's host functions library:
function readFromFile(path) {
var result = target.host().performTaskWithPathArgumentsTimeout("/bin/cat", [path], 10);
// be verbose if something didn't go well
if (0 != result.exitCode) {
throw new Error("readFromFile failed: " + result.stderr);
}
return result.stdout;
}
If you are using Illuminator, this is host().readFromFile(path).

Categories

Resources