Papa Parse CSV for React Native - ios

Using PapaParse, I am trying to parse a CSV located locally on an iOS device. The sample code below is pretty straight forward except that it does not take a file path. I do have the path to the local file but I'm not sure how properly insert that in place of fileInput.files[0]. I tried using File() to create a file from the path but could not get anywhere. How can I parse a local csv, in react native using PapaParse?
Papa.parse(fileInput.files[0], {
complete: function(results) {
console.log(results);
}
});

Just to add to Answer above by #pnizzle.
For some reason you can access Image files as long as they are in your React Native project's directory, with a relative path from your current js file.
For CSV file I had to bundle them with my iOS project (I grouped the files in a Assets folder) then use RNFS to get the path for my MainBundleDirectory and access my .CSV files from there.
Hope this helps anyone else in a similar bind.
var mainBundlePath = RNFS.MainBundlePath;
var path = '/Assets/CSVData.csv';
Papa.parse(mainBundlePath+path, {
download: true,
delimiter: '\t',
complete: function(results) {
console.log('This is ME..');
console.log(results);
}
});

UPDATE: You must first import the file, just as you would a component.
import myDataset from '../path/to/myDataset.csv';
Then you will use myDataset as your file to download with Papa.parse like so...
Papa.parse(myDataset, {
download: true,
delimiter: '\t'
complete: function(results) {
console.log(results);
}
});
Specify a config value for download as true.
Delimiter should be auto-detected, as per Papa Parse documentation.

Related

How to get the current path of an electron js portable app?

Hello fellow developers/programmers. Today I come to ask for help with something, and is that I'm making an app that if or if it has to be portable, the problem I'm having is that when writing a zip file the app does not find the directories or generates the zip corruptly.
My code that writes the zip file looks like this:
ipcMain.on("report-file", async (event, data) => {
let zipFilePath = "report.zip"
let output = fs.createWriteStream(zipFilePath);
let archive = archiver("zip")
archive.pipe(output);
if (data.saves) {
archive.directory(`game/saves`, false)
archive.directory(`game/cache`, false)
}
archive.append(fs.createReadStream(`log.txt`), {
name: `log.txt`,
})
archive.append(fs.createReadStream(`traceback.txt`), {
name: `traceback.txt`,
})
archive.finalize()
});
Electron Version: 21.2.3
SO: Windows 11
electron-builder Version: 23.6.0
Looking a little more in depth, I found that the app is using the address
C:\User\User\AppData\Local\Temp\[id]\resources\app.asar
and it is trying to compress the files as if they were in that path, however, the files to compress are located where the .exe is. (G:\myapp\dist)
I already tried to fix it by following an old post on the stackoverflow page, however, it didn't solve the problem, so today I decided to ask my question here, do you have any idea how to get the actual path of an electron js portable app?
I found the solution to this, and it was to create a dialog with electron, and load the folder location. Then use resolve together with the address of the executable, this way it loads correctly the address of the folder where the exe is located.
let dir
dir = await dialog.showOpenDialog(win, {
properties: ['openDirectory'],
defaultPath: path.resolve('.', process.env.PORTABLE_EXECUTABLE_DIR)
});

How can I upload one file at a time using sendKeys() in protractor

In my project, I have a webpage where I can drag & drop a file, when doing e2e testing by protractor, I have to upload it using sendKeys() with the absolute path of my file, here is test script:
var path = require('path');
var remote = require('selenium-webdriver/remote');
it("===> it will upload document", function () {
browser.setFileDetector(new remote.FileDetector());
let exePath = path.resolve(__dirname, '../bbb/' + fileName);
$('button[type="button"],[type="file"]').isDisplayed().then(function () {
$('input[type="file"]').sendKeys(exePath);
});
});
it's working well when I upload 1st file, but when I tried to upload 2nd file using the same code but just update the filename, The 1st uploaded file is automatically uploaded again alone with the 2nd file, instead of only uploading the 2nd file, so I got double 1st file which is not expected. would like to find a way to upload one file at a time, please help, thanks.

File path in production mode

Developing an app in electron, everything is working fine with file path in development mode. I created the "documents" folder, in which documents will be stored.
var dir = path.join(__dirname, 'documents');
fs.readdir(dir, function (err, files) {
if (err) {
console.log('Unable to scan directory: ' + err);
}
var files_with_dirs = files.map(function(name) {
return (dir + '/'+ name);
});
This code return all files in "documents" folder.
But in production mode when i pack my app, a folder with many files is created, the path becomes like this.
How to solve this problem?
For paths pointing to internal resources, I'd suggest using a relative path and building it on the fly
var p = upath.toUnix(upath.join(__dirname, "documents", "this-image.jpg));
Where __dirname is the path to the currently executing file.
I use the upath toUnix function because it normalizes the path to use forward slashes – which has worked better for me with cross--platform apps..

How to download and retrieve local files on iOS with react native and react-native-fetch-blob?

I'm using react-native-fetch-blob to download mp3 files and then playing them later. The problem is that the actual path for RNFetchBlob.fs.dirs.DocumentDir changes when I close the app and restart again, which means I can't use the absolute file path I stored right after downloading the files retrieve the files in the next run of the app.
Here's my code for downloading and storing the file paths:
export function downloadAudio(urlArray) { //download every section in the urlArray
return (dispatch) => {
Promise.all(urlArray.map(section => {
dispatch(startDownload(section.section_id))
console.log('download start for id = ',section.section_id ) //start download
return RNFetchBlob
.config({
path: RNFetchBlob.fs.dirs.DocumentDir + '/courseSections/' + section.section_id + '.mp3',
appendExt: 'mp3'
})
.fetch('GET', section.section_url, {
'Cache-Control': 'no-store'
})
.progress({ count: 10 }, (received, total) => {
console.log(`progress for section ${section.section_id}: `, Math.floor(received/total*100), '%')
dispatch(downloadProgress({id: section.section_id, progress: Math.floor(received/total*100)/100}))
})
.then(res => {
console.log(`section ${section.section_id} is saved to: `, res.path())
return { path: res.path(), id: section.section_id }
})
.then(pathInfo => dispatch(downloadSuccess(pathInfo))) //download finished
}))
.catch((error, statusCode) => {
console.log(statusCode, ' error: ', error)
})
}
}
I stored { path: res.path(), id: section.section_id } as part of persisted app state. But it's not useful cuz next time I open the app, the file path has been reassigned. For example, here's the path one file was downloaded to:
downloaded file path
But after I close the app and restart, the path is changed to:
/Users/NatashaChe/Library/Developer/CoreSimulator/Devices/830778DE-3CE3-4FC7-AA4B-DFBAE999751C/data/Containers/Data/Application/0C47E33F-ACF8-4539-9456-8FF3E8FBECB2/Documents/courseSections/14.mp3
i.e. the files got assigned to a different sub-folder under the Application folder.
Obviously the audio player (I'm using react-native-sound) can't find the file using the original path that the app has stored. So my question is: Is there a way I can fix the path? Or is there some other way of retrieving files that I'm not aware of?
And also, I'm using the iOS simulator on my computer. Haven't tried this on the phone yet. Does anyone know if the above code can be directly used on iphone and have the file saved to my app's directory? Or shall I set the file path in any other way?
I'm using react native 0.41.
I made the following change to make it work, at least on simulator for now. Not sure what'd happen on an actual phone.
When retrieving the file, instead of using the file path as returned by res.path() as in the code above, I now directly use filePath = RNFetchBlob.fs.dirs.DocumentDir + '/courseSections/' + sectionInfo.section.section_id + '.mp3' when retrieving the file.

How to create a Firefox theme (addon?) from a simple stylesheet?

I have created a theme for Firefox that involve a simple stylesheet. I am currently using Stylish extension for this but would like to share my theme as an Firefox addon (since Theme are simple image).
I didn't quickly find anything about that in search engine and only find an outdated ressource on MDN.
Any tip to make share this CSS as an addon? (bonus: automate release from a git repo)
If it's a simple stylesheet as you described, then you would have to attach the stylesheet to the nsIDOMWindow. Example code with addon-sdk
const { attachTo, detachFrom } = require("sdk/content/mod");
const { Style } = require("sdk/stylesheet/style");
const { getMostRecentWindow } = require("sdk/window/utils");
const { browserWindows } = require("sdk/windows");
const { viewFor } = require("sdk/view/core");
const style = Style({
uri: "./index.css" // path to file
});
attachTo(style, getMostRecentWindow());
browserWindows.on("open", function(window) {
attachTo(style,viewFor(window));
});
require("sdk/system/unload").when(function() {
for (let window of browserWindows)
detachFrom(style, viewFor(window));
});
EDIT:
To start using addon-sdk you must have jpm. Here it is described how to install it. Once you installed it, you should create a directory that will contain your extension. Then open a terminal/console and type jpm init. Fill the prompted fields according to your needs. You can also check out these additional options available in the package.json (it's in the root of your directory with the extension) and use them aswell.
The next step is to paste my code in the index.js (you can paste the code somewhere else but then you have to import that file using require). Create a directory "data" in the extension directory and create a file with stylesheet there. Then replace "index.css" here
uri: "./index.css"
with your file name.
Once you are done, type jpm xpi in your terminal/console and your extension is ready to install! Good luck

Resources