MCPcopy Create free account
hub / github.com/facebook/memlab / readFile

Method readFile

packages/core/src/lib/StringLoader.ts:45–122  ·  view source on GitHub ↗
(file: string, options: ReadFileOptions = {})

Source from the content-addressed store, hash-verified

43 // 1) starts with options.startSignature
44 // 2) ends with options.endSignature
45 readFile(file: string, options: ReadFileOptions = {}): Promise<string> {
46 const _buffer = Buffer.alloc(1024 * 1024); // 1MB
47 const _fd = fs.openSync(file, 'r');
48
49 const _startSig = options.startSignature;
50 const _endSig = options.endSignature;
51 const _errHandler = this.processErrorIfNotNull;
52 const inclusive = !!options.inclusive;
53
54 let _resolve: (result: string) => void;
55 let _result = '';
56 let _begin = false;
57 let _end = false;
58 let _pos = 0;
59
60 const readCallback = function (err: NodeFSError, bytes: number) {
61 _errHandler(err);
62
63 const str = _buffer.slice(0, bytes).toString('utf8');
64
65 if (!_begin && !_startSig) {
66 // start reserving content if no start signature is specified
67 _begin = true;
68 }
69
70 _result += str;
71
72 // look for start signature
73 if (!_begin && _startSig != null) {
74 const idx = _result.indexOf(_startSig);
75 if (idx >= 0) {
76 _begin = true;
77 _result = _result.substring(idx + _startSig.length);
78 } else if (_result.length > _startSig.length) {
79 _result = _result.substring(_result.length - _startSig.length);
80 }
81 }
82
83 // look for end signature
84 if (_begin && _endSig) {
85 let searchIdx = Math.max(
86 0,
87 _result.length - str.length - _endSig.length,
88 );
89 if (_startSig && searchIdx < _startSig.length) {
90 searchIdx = _startSig.length;
91 }
92 const idx = _result.indexOf(_endSig, searchIdx);
93 if (idx >= 0) {
94 _result = _result.substring(0, idx);
95 _end = true;
96 }
97 }
98
99 if (_end || bytes < _buffer.length) {
100 if (!_begin) {
101 _result = '';
102 }

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected