feat(file-system): append, appendText & createFile (#10285)

This commit is contained in:
Osei Fortune
2023-05-04 23:45:01 -04:00
committed by GitHub
parent 7bb0918e08
commit ab32aeaaa3
36 changed files with 2079 additions and 654 deletions

View File

@ -5,7 +5,7 @@ import * as fs from '@nativescript/core/file-system';
import * as TKUnit from '../tk-unit';
import * as appModule from '@nativescript/core/application';
import { isIOS, Device, platformNames } from '@nativescript/core';
import { isIOS, Device, platformNames, isAndroid } from '@nativescript/core';
export var testPathNormalize = function () {
// >> file-system-normalize
@ -719,3 +719,62 @@ export function test_FileCopy(done) {
.then(() => done())
.catch(done);
}
export function testAndroidCreate() {
let testFunc = function testFunc() {
const file = fs.File.android.createFile({
directory: fs.AndroidDirectory.DOWNLOADS,
name: `${Date.now()}.txt`,
mime: 'text/plain',
relativePath: `NativeScript`,
});
file.writeTextSync('some text');
return file;
};
if (isAndroid) {
const file = testFunc();
TKUnit.assertEqual(file.readTextSync(), 'some text', `The contents of the new file created in the 'AndroidDirectory.DOWNLOADS' folder are not as expected.`);
file.removeSync();
TKUnit.assertTrue(!fs.File.exists(file.path));
} else {
TKUnit.assertThrows(testFunc, `Trying to retrieve createFile on a platform different from Android should throw!`, `createFile is available on Android only!`);
}
}
export function test_FileAppend(done) {
const content = 'Hello World';
const hello_world = global.isIOS ? NSString.stringWithString(content).dataUsingEncoding(NSUTF8StringEncoding) : new java.lang.String(content).getBytes('UTF-8');
const file = fs.File.fromPath(fs.path.join(fs.knownFolders.temp().path, `${Date.now()}-app.txt`));
file
.appendText('Hello')
.then(() => file.appendText(' World'))
.then(() => {
TKUnit.assert(file.size === hello_world.length);
return file.readText();
})
.then((value) => {
TKUnit.assert(value === content);
return Promise.allSettled([file.remove()]);
})
.then(() => done())
.catch(done);
}
export function test_FileAppendText(done) {
const content = 'Hello World';
const file = fs.File.fromPath(fs.path.join(fs.knownFolders.temp().path, `${Date.now()}-app.txt`));
file
.appendText('Hello')
.then(() => file.appendText(' World'))
.then(() => file.readText())
.then((value) => {
TKUnit.assert(value === content);
return Promise.allSettled([file.remove()]);
})
.then(() => done())
.catch(done);
}

View File

@ -1,4 +1,4 @@
import { Page, EventData, Application, File, Folder, knownFolders, path, getFileAccess, Utils } from '@nativescript/core';
import { Page, EventData, Application, File, Folder, knownFolders, path, getFileAccess, Utils, Screen, Http, AndroidDirectory, ImageSource, alert } from '@nativescript/core';
let page: Page;
@ -217,3 +217,103 @@ function getFileNameFromContent(content: string) {
const file = getFileAccess().getFile(content);
return decodeURIComponent(file.name).split('/').pop().toLowerCase();
}
let lastDownload: File;
export function createFileInDownloads() {
if (!global.isAndroid) {
return;
}
const width = Screen.mainScreen.widthPixels;
const height = Screen.mainScreen.heightPixels;
const randomImageUrl = `https://picsum.photos/${width}/${height}.jpg?random=${Date.now()}`;
Http.getFile(randomImageUrl).then((result: File) => {
let file = File.android.createFile({
directory: AndroidDirectory.DOWNLOADS,
name: `${Date.now()}.jpg`,
mime: 'image/jpeg',
relativePath: `NativeScript`,
});
result
.copy(file.path)
.then((done) => {
lastDownload = file;
console.log('done: ' + done + '\n' + 'Original path: ' + result.path + '\n' + 'Copied to: ' + file.path + '\n' + 'Original size: ' + result.size + '\n' + 'Copy size: ' + file.size + '\n');
alert(`File saved in ${AndroidDirectory.DOWNLOADS}/NativeScript`);
})
.catch((error) => {
console.error(error);
});
});
}
export function createFileInGallery() {
if (!global.isAndroid) {
return;
}
const width = Screen.mainScreen.widthPixels;
const height = Screen.mainScreen.heightPixels;
const randomImageUrl = `https://picsum.photos/${width}/${height}.jpg?random=${Date.now()}`;
Http.getFile(randomImageUrl).then((result: File) => {
let file = File.android.createFile({
directory: AndroidDirectory.PICTURES,
name: `${Date.now()}.jpg`,
mime: 'image/jpeg',
relativePath: `NativeScript`,
});
result
.copy(file.path)
.then((done) => {
console.log('done: ' + done + '\n' + 'Original path: ' + result + '\n' + 'Copied to: ' + file.path + '\n' + 'Original size: ' + result.size + '\n' + 'Copy size: ' + file.size + '\n');
alert(`File saved in ${AndroidDirectory.PICTURES}/NativeScript`);
})
.catch((error) => {
console.error(error);
});
});
}
export function createFileInMusic() {
if (!global.isAndroid) {
return;
}
Http.getFile('https://github.com/rafaelreis-hotmart/Audio-Sample-files/raw/master/sample.mp3').then((result: File) => {
let file = File.android.createFile({
directory: AndroidDirectory.MUSIC,
name: `${Date.now()}.MP3`,
mime: 'audio/mp3',
relativePath: `NativeScript/MP3`,
});
result
.copy(file.path)
.then((done) => {
console.log('done: ' + done + '\n' + 'Original path: ' + result + '\n' + 'Copied to: ' + file.path + '\n' + 'Original size: ' + result.size + '\n' + 'Copy size: ' + file.size + '\n');
alert(`File saved in ${AndroidDirectory.MUSIC}/NativeScript/MP3`);
})
.catch((error) => {
console.error(error);
});
});
}
export function createAndAppendText() {
const file = File.fromPath(path.join(knownFolders.temp().path, `${Date.now()}-app.txt`));
file.appendTextSync('Hello');
file.appendTextSync(' World');
const data = file.readTextSync();
console.log('createAndAppend:', data === 'Hello World');
}
export function createAndAppendData() {
const file = File.fromPath(path.join(knownFolders.temp().path, `${Date.now()}-app.txt`));
const hello = global.isIOS ? NSString.stringWithString('Hello').dataUsingEncoding(NSUTF8StringEncoding) : new java.lang.String('Hello').getBytes('UTF-8');
const world = global.isIOS ? NSString.stringWithString(' World').dataUsingEncoding(NSUTF8StringEncoding) : new java.lang.String(' World').getBytes('UTF-8');
file.appendSync(hello);
file.appendSync(world);
const data = file.readTextSync();
console.log('createAndAppendData:', data === 'Hello World');
}

View File

@ -5,5 +5,10 @@
<Button text="Pick File" tap="pickFile" />
<Button text="Pick Multiple Files" tap="pickFiles" />
<Button text="Test Copy" tap="copyTest" />
<Button text="External File Creation" tap="createFileInDownloads" />
<Button text="Add file to gallery" tap="createFileInGallery" />
<Button text="Add file to music" tap="createFileInMusic" />
<Button text="Append Text" tap="createAndAppendText" />
<Button text="Append Data" tap="createAndAppendData" />
</StackLayout>
</Page>