Nik S.
Nik S.

Reputation: 51

How to reference a local file in a NativeScript mobile app

I am trying to read from a .txt file located within the project structure. After the app has been compiled to the device (tested on both Android and iOS), I begin by checking if the file exists. It does not seem to.

fileAccess.ts:

import fs = require("file-system");

export class FileAccess
{
    public data(filePath: string)
    {
        let exists = fs.File.exists(filePath);
        console.log(exists);
    }
}

test.txt (located in same directory as fileAccess.ts):

1;DAC

Calling data("./test.txt"); on an instance of FileAccess, the console prints false.

I assume that either I am referencing the file wrong, or the file is not being copied to the device. But which is it, and how do I fix it?

Upvotes: 1

Views: 1991

Answers (1)

Eddy Verbruggen
Eddy Verbruggen

Reputation: 3550

You could use knownFolders for that. Assuming test.txt is in the root of the app folder:

let appPath = fs.knownFolders.currentApp().path; let myTextFile = appPath + "/test.txt"

Upvotes: 6

Related Questions