From de75e6420b7382ee3abc73d9c6b4d80408f69cc5 Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Tue, 20 Dec 2016 12:18:11 -0200 Subject: [PATCH] Add react-native-fs (#13437) * add react-native-fs * reference types * add tslint.json * fix lint errors --- react-native-fs/index.d.ts | 190 +++++++++++++++++++++++ react-native-fs/react-native-fs-tests.ts | 119 ++++++++++++++ react-native-fs/tsconfig.json | 21 +++ react-native-fs/tslint.json | 1 + 4 files changed, 331 insertions(+) create mode 100644 react-native-fs/index.d.ts create mode 100644 react-native-fs/react-native-fs-tests.ts create mode 100644 react-native-fs/tsconfig.json create mode 100644 react-native-fs/tslint.json diff --git a/react-native-fs/index.d.ts b/react-native-fs/index.d.ts new file mode 100644 index 0000000000..a700005032 --- /dev/null +++ b/react-native-fs/index.d.ts @@ -0,0 +1,190 @@ +// Type definitions for react-native-fs 2.0 +// Project: https://github.com/johanneslumpe/react-native-fs +// Definitions by: Paulo Cesar +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace RNFS { + interface ReadDirItem { + // The name of the item + name: string; + // The absolute path to the item + path: string; + // Size in bytes + size: string; + // Is the file just a file? + isFile(): boolean; + // Is the file a directory? + isDirectory(): boolean; + } + + interface StatResult { + // The name of the item + name: string; + // The absolute path to the item + path: string; + // Size in bytes + size: string; + // UNIX file mode + mode: number; + // Is the file just a file? + isFile(): boolean; + // Is the file a directory? + isDirectory(): boolean; + } + + interface Headers { + [index: string]: string; + } + type Fields = Headers; + + interface MkdirOptions { + // iOS only + NSURLIsExcludedFromBackupKey?: boolean; + } + + interface DownloadResult { + // The download job ID, required if one wishes to cancel the download. See `stopDownload`. + jobId: number; + // The HTTP status code + statusCode: number; + // The number of bytes written to the file + bytesWritten: number; + } + + type DownloadCallbackBegin = (res: DownloadBeginCallbackResult) => void; + type DownloadCallbackProgress = (res: DownloadProgressCallbackResult) => void; + + interface DownloadFileOptions { + // URL to download file from + fromUrl: string; + // Local filesystem path to save the file to + toFile: string; + // An object of headers to be passed to the server + headers?: Headers; + background?: boolean; + progressDivider?: number; + begin?: DownloadCallbackBegin; + progress?: DownloadCallbackProgress; + } + + interface DownloadProgressCallbackResult { + // The download job ID, required if one wishes to cancel the download. See `stopDownload`. + jobId: number; + // The total size in bytes of the download resource + contentLength: number; + // The number of bytes written to the file so far + bytesWritten: number; + } + + interface DownloadBeginCallbackResult { + // The download job ID, required if one wishes to cancel the download. See `stopDownload`. + jobId: number; + // The HTTP status code + statusCode: number; + // The total size in bytes of the download resource + contentLength: number; + // The HTTP response headers from the server + headers: Headers; + } + + type UploadCallbackBegin = (res: UploadBeginCallbackResult) => void; + type UploadCallbackProgress = (res: UploadProgressCallbackResult) => void; + + interface UploadFileOptions { + // URL to upload file to + toUrl: string; + // An array of objects with the file information to be uploaded. + files: UploadFileItem[]; + // An object of headers to be passed to the server + headers?: Headers; + // An object of fields to be passed to the server + fields?: Fields; + // Default is 'POST', supports 'POST' and 'PUT' + method?: string; + begin?: UploadCallbackBegin; + progress?: UploadCallbackProgress; + } + + interface UploadResult { + // The upload job ID, required if one wishes to cancel the upload. See `stopUpload`. + jobId: number; + // The HTTP status code + statusCode: number; + // The HTTP response headers from the server + headers: Headers; + // The HTTP response body + body: string; + } + + interface UploadFileItem { + // Name of the file, if not defined then filename is used + name: string; + // Name of file + filename: string; + // Path to file + filepath: string; + // The mimetype of the file to be uploaded, if not defined it will get mimetype from `filepath` extension + filetype: string; + } + + interface UploadBeginCallbackResult { + // The upload job ID, required if one wishes to cancel the upload. See `stopUpload`. + jobId: number; + } + + interface UploadProgressCallbackResult { + // The upload job ID, required if one wishes to cancel the upload. See `stopUpload`. + jobId: number; + // The total number of bytes that will be sent to the server + totalBytesExpectedToSend: number; + // The number of bytes sent to the server + totalBytesSent: number; + } + + interface FSInfoResult { + // The total amount of storage space on the device (in bytes). + totalSpace: number; + // The amount of available storage space on the device (in bytes). + freeSpace: number; + } + + interface JobReturnValue { + jobId: number; + promise: Promise; + } + + // The absolute path to the main bundle directory + export const MainBundlePath: string; + // The absolute path to the caches directory + export const CachesDirectoryPath: string; + // The absolute path to the document directory + export const DocumentDirectoryPath: string; + // The absolute path to the temporary directory (iOS only) + export const TemporaryDirectoryPath: string; + // The absolute path to the external files, shared directory (android only) + export const ExternalDirectoryPath: string; + // The absolute path to the external storage, shared directory (android only) + export const ExternalStorageDirectoryPath: string; + + export function readDir(path: string): Promise; + export function readdir(path: string): Promise; + export function stat(filepath: string): Promise; + export function readFile(filepath: string, encoding?: string): Promise; + export function unlink(filepath: string): Promise; + export function writeFile(filepath: string, contents: string, encoding?: string): Promise; + export function appendFile(filepath: string, contents: string, encoding?: string): Promise; + export function moveFile(filepath: string, destPath: string): Promise; + export function copyFile(filepath: string, destPath: string): Promise; + export function exists(filepath: string): Promise; + export function hash(filepath: string, algorithm: string): Promise; + export function mkdir(filepath: string, options?: MkdirOptions): Promise; + export function downloadFile(options: DownloadFileOptions): JobReturnValue; + export function stopDownload(jobId: number): Promise; + export function uploadFiles(options: UploadFileOptions): JobReturnValue; + export function stopUpload(jobId: number): Promise; + export function getFSInfo(): Promise; +} + +export = RNFS; \ No newline at end of file diff --git a/react-native-fs/react-native-fs-tests.ts b/react-native-fs/react-native-fs-tests.ts new file mode 100644 index 0000000000..0e7dc2b0d0 --- /dev/null +++ b/react-native-fs/react-native-fs-tests.ts @@ -0,0 +1,119 @@ +import * as RNFS from 'react-native-fs'; + + +// get a list of files and directories in the main bundle +RNFS.readDir(RNFS.MainBundlePath) // On Android, use "RNFS.DocumentDirectoryPath" (MainBundlePath is not defined) + .then((result) => { + console.log('GOT RESULT', result); + + // stat the first file + return Promise.all([RNFS.stat(result[0].path), result[0].path]); + }) + .then((statResult) => { + if (statResult[0].isFile()) { + // if we have a file, read it + return RNFS.readFile(statResult[1], 'utf8'); + } + + return 'no file'; + }) + .then((contents) => { + // log the file contents + console.log(contents); + }) + .catch((err) => { + console.log(err.message, err.code); + }); + +// create a path you want to write to +var path = RNFS.DocumentDirectoryPath + '/test.txt'; + +// write the file +RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8') + .then(() => { + console.log('FILE WRITTEN!'); + }) + .catch((err) => { + console.log(err.message); + }); + +RNFS.unlink('path') + .then(() => { + console.log('FILE DELETED'); + }) + // `unlink` will throw an error, if the item to unlink does not exist + .catch((err) => { + console.log(err.message); + }); + +var uploadUrl = 'http://requestb.in/XXXXXXX'; // For testing purposes, go to http://requestb.in/ and create your own link +// create an array of objects of the files you want to upload +var files = [ + { + name: 'test1', + filename: 'test1.w4a', + filepath: RNFS.DocumentDirectoryPath + '/test1.w4a', + filetype: 'audio/x-m4a' + }, { + name: 'test2', + filename: 'test2.w4a', + filepath: RNFS.DocumentDirectoryPath + '/test2.w4a', + filetype: 'audio/x-m4a' + } +]; + +var uploadBegin: RNFS.UploadCallbackBegin = (response) => { + var jobId = response.jobId; + console.log('UPLOAD HAS BEGUN! JobId: ' + jobId); +}; + +var uploadProgress: RNFS.UploadCallbackProgress = (response) => { + var percentage = Math.floor((response.totalBytesSent/response.totalBytesExpectedToSend) * 100); + console.log('UPLOAD IS ' + percentage + '% DONE!'); +}; + +// upload files +RNFS.uploadFiles({ + toUrl: uploadUrl, + files: files, + method: 'POST', + headers: { + 'Accept': 'application/json', + }, + fields: { + 'hello': 'world', + }, + begin: uploadBegin, + progress: uploadProgress +}).promise.then((response) => { + if (response.statusCode == 200) { + console.log('FILES UPLOADED!'); // response.statusCode, response.headers, response.body + } else { + console.log('SERVER ERROR'); + } + }) + .catch((err) => { + if(err.description === "cancelled") { + // cancelled by user + } + console.log(err); + }); + +var downloadProgress: RNFS.DownloadCallbackProgress = (result) => { + result.bytesWritten === 0 + result.contentLength > 10 + result.jobId +} + +var downloadBegin: RNFS.DownloadCallbackBegin = (result) => { + result.headers === {} +} + +RNFS.downloadFile({ + fromUrl: 'http://.txt', + toFile: 'file.txt', + begin: downloadBegin, + progress: downloadProgress +}).promise.then((response) => { + response.statusCode === 200 +}) \ No newline at end of file diff --git a/react-native-fs/tsconfig.json b/react-native-fs/tsconfig.json new file mode 100644 index 0000000000..a11b66853f --- /dev/null +++ b/react-native-fs/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "noUnusedParameters": true, + "noUnusedLocals": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-native-fs-tests.ts" + ] +} \ No newline at end of file diff --git a/react-native-fs/tslint.json b/react-native-fs/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/react-native-fs/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file