Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get `__dirname` like Node.js using react native

I want to get current javascript script's dirname name, such as __dirname in node.js. I haven't found the method in the document in react native , and I wonder how to achieve this purpose? Or how can I locate the static file (e.g. .js)? For example like using NSDocumentDirectory to locate a file natively in iOS.

like image 759
user2400870 Avatar asked Nov 30 '25 16:11

user2400870


1 Answers

One way to do it would be to create a native module. Here's an example of a really simple one that just gets you a string, which you could customise for your exact requirements. In Xcode, create a new class:

//  DirName.h

#import "RCTBridgeModule.h"

@interface DirName : NSObject<RCTBridgeModule>

@end

//  DirName.m
#import "DirName.h"

@implementation DirName
- (void) get:(RCTResponseSenderBlock)callback {
    RCT_EXPORT();

    // Change this depending on what you want to retrieve:
    NSString* dirName = @"something";

    callback(@[dirName]);
}

@end

Then call it with:

var dirName = require('NativeModules').DirName;

dirName.get(dirName => {
    console.log(dirName);
});

However I'd caveat this. Have a think about what you're doing - do you definitely want to read the filesystem of your iOS device or do you want to use one of the other methods of grabbing documents which is available to you?

like image 80
Colin Ramsay Avatar answered Dec 03 '25 14:12

Colin Ramsay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!