fs#readFile TypeScript Examples
The following examples show how to use
fs#readFile.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: streaming-delegate.ts From homebridge-nest-cam with GNU General Public License v3.0 | 6 votes |
private getOfflineImage(callback: SnapshotRequestCallback): void {
const log = this.log;
readFile(join(__dirname, `../images/offline.jpg`), (err, data) => {
if (err) {
log.error(err.message);
callback(err);
} else {
callback(undefined, data);
}
});
}
Example #2
Source File: BibTeXCitations.ts From vscode-markdown-notes with GNU General Public License v3.0 | 6 votes |
private static bibTeXFile(): Promise<string> {
const path = this.bibTexFilePath();
if (path == null || path == '') {
return Promise.reject('BibTeX file location not set');
}
return new Promise((resolve, reject) => {
readFile(path, (error, buffer) => {
if (error) {
reject(error);
} else {
resolve(buffer.toString());
}
});
});
}
Example #3
Source File: NoteParser.ts From vscode-markdown-notes with GNU General Public License v3.0 | 6 votes |
// read fsPath into this.data and return a
// Promise that resolves to `this` Note instance.
// Usage:
// note.readFile().then(note => console.log(note.data));
readFile(useCache = false): Promise<Note> {
// console.debug(`readFile: ${this.fsPath}`);
let that = this;
// if we are using the cache and cached data exists,
// just resolve immediately without re-reading files
if (useCache && this.data) {
return new Promise((resolve) => {
resolve(that);
});
}
// make sure we reset parsed to false because we are re-reading the file
// and we don't want to end up using the old parsed refCandidates
// in the event that parseData(true) is called in the interim
this._parsed = false;
return new Promise((resolve, reject) => {
readFile(that.fsPath, (err, buffer) => {
if (err) {
reject(err);
} else {
// NB! Make sure to cast this to a string
// otherwise, it will cause weird silent failures
that.data = `${buffer}`;
resolve(that);
}
});
});
}
Example #4
Source File: NoteParser.ts From vscode-markdown-notes with GNU General Public License v3.0 | 6 votes |
// call this when we know a file has changed contents to update the cache
static updateCacheFor(fsPath: string) {
let that = this;
let note = NoteParser.parsedFileFor(fsPath);
note.readFile(false).then((_pf) => {
_pf.parseData(false);
// remember to set in the master index:
that._notes[fsPath] = _pf;
});
}
Example #5
Source File: writeGitIgnore.ts From engine with MIT License | 6 votes |
pReadFile = promisify(readFile)
Example #6
Source File: file-handler.ts From karma-test-explorer with MIT License | 6 votes |
public async readFile(filePath: string, encoding?: BufferEncoding): Promise<string> {
this.logger.debug(() => `Reading file async: ${filePath}`);
const deferredFileContents = new DeferredPromise<string>();
readFile(filePath, encoding ?? this.fileEncoding, (error, data) => {
if (error) {
this.logger.error(() => `Failed reading file ${filePath}: ${error}`);
deferredFileContents.reject(new Error(`Failed to read file '${filePath}': ${error}`));
} else {
this.logger.trace(() => `Done reading file ${filePath}: ${error}`);
deferredFileContents.fulfill(data?.toString());
}
});
return deferredFileContents.promise();
}
Example #7
Source File: data.service.ts From tabby with MIT License | 6 votes |
_readData(): Promise<string> {
return new Promise((resolve, reject) => {
this.isFileExist();
readFile(this.app.getPath('userData') + '/data.json', "utf-8", (err, data2) => {
if(err) return reject(err);
if(data2.length === 0) {
this.writeDefaultData();
this.readData();
} else {
return resolve(data2);
}
});
});
}
Example #8
Source File: importUser.ts From avalanchejs with BSD 3-Clause "New" or "Revised" License | 6 votes |
main = async (): Promise<any> => {
const path: string = "./examples/secrets.json"
const encoding: "utf8" = "utf8"
const cb = async (err: any, data: any): Promise<void> => {
if (err) throw err
const jsonData: any = JSON.parse(data)
const username: string = "username"
const password: string = jsonData.password
const user: string = jsonData.user
const successful: boolean = await keystore.importUser(
username,
user,
password
)
console.log(successful)
}
readFile(path, encoding, cb)
}
Example #9
Source File: revokeToken.ts From avalanchejs with BSD 3-Clause "New" or "Revised" License | 6 votes |
main = async (): Promise<any> => {
const path: string = "./examples/secrets.json"
const encoding: "utf8" = "utf8"
const cb = async (err: any, data: any): Promise<void> => {
if (err) throw err
const jsonData: any = JSON.parse(data)
const password: string = jsonData.password
const token: string = jsonData.token
const successful: boolean = await auth.revokeToken(password, token)
console.log(successful)
}
readFile(path, encoding, cb)
}
Example #10
Source File: newToken.ts From avalanchejs with BSD 3-Clause "New" or "Revised" License | 6 votes |
main = async (): Promise<any> => {
const path: string = "./examples/secrets.json"
const encoding: "utf8" = "utf8"
const cb = async (err: any, data: any): Promise<void> => {
if (err) throw err
const jsonData: any = JSON.parse(data)
const password: string = jsonData.password
const endpoints: string[] = ["*"]
const token: string | ErrorResponseObject = await auth.newToken(
password,
endpoints
)
console.log(token)
}
readFile(path, encoding, cb)
}
Example #11
Source File: changePassword.ts From avalanchejs with BSD 3-Clause "New" or "Revised" License | 6 votes |
main = async (): Promise<any> => {
const path: string = "./examples/secrets.json"
const encoding: "utf8" = "utf8"
const cb = async (err: any, data: any): Promise<void> => {
if (err) throw err
const jsonData: any = JSON.parse(data)
const oldPassword: string = jsonData.oldPassword
const newPassword: string = jsonData.newPassword
const successful: boolean = await auth.changePassword(
oldPassword,
newPassword
)
console.log(successful)
}
readFile(path, encoding, cb)
}
Example #12
Source File: package.json.ts From aurelia-mdc-web with MIT License | 6 votes |
/**
* Reads and parses the content of a package.json file
*
* @param pathSegments - The path segments of the folder where the package.json is located, relative to the root of the project
*/
export async function loadPackageJson(): Promise<Package> {
const path = 'package.json';
return new Promise((resolve, reject) => {
readFile(path, (err, data) => {
if (err) {
reject(err);
}
if (!data) {
throw new Error(`Empty file: ${path}`);
}
const str = data.toString('utf8');
const json = JSON.parse(str);
resolve(json);
});
});
}
Example #13
Source File: Util.ts From vscode-sound-player with MIT License | 6 votes |
export async function GetWebviewContent(rootPath: string): Promise<string> {
const htmlPath = resolve(rootPath, 'index.html')
const htmlContent = await new Promise<string>((resolve, reject) => readFile(htmlPath, 'utf-8', (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
}))
return htmlContent.replace(/(<script.+?src="|<link.+?href=")(.+?)"/g, (match, $1, $2) => {
return `${$1}${Uri.file(resolve(rootPath, $2)).with({ scheme: 'vscode-resource' })}"`
})
}
Example #14
Source File: jsonHelper.ts From amplication with Apache License 2.0 | 6 votes |
static read: (path: string) => Promise<JsonObject> = (
path: string
): Promise<any> => {
return new Promise<any>((resolve, reject) => {
readFile(path, (err: NodeJS.ErrnoException | null, data: Buffer) => {
if (err) {
reject(err);
} else {
try {
resolve(JSON.parse(data.toString()));
} catch (e) {
reject(e);
}
}
});
});
};
Example #15
Source File: fileSystem.ts From hermes-profile-transformer with MIT License | 6 votes |
readFileAsync = async (path: string): Promise<any> => {
try {
const readFileAsync = promisify(readFile);
const fileString: string = (await readFileAsync(path, 'utf-8')) as string;
if (fileString.length === 0) {
throw new Error(`${path} is an empty file`);
}
const obj = JSON.parse(fileString);
return obj;
} catch (err) {
throw err;
}
}
Example #16
Source File: FileStorage.ts From beacon-sdk with MIT License | 6 votes |
/* eslint-disable prefer-arrow/prefer-arrow-functions */
export function readLocalFile(): Promise<JsonObject> {
return new Promise((resolve: (_: JsonObject) => void, reject: (error: unknown) => void): void => {
readFile(file, { encoding: 'utf8' }, (fileReadError: unknown, fileContent: string) => {
if (fileReadError) {
reject(fileReadError)
}
try {
const json: JsonObject = JSON.parse(fileContent)
resolve(json)
} catch (jsonParseError) {
reject(jsonParseError)
}
})
})
}
Example #17
Source File: settings.ts From vscode-windows-terminal with MIT License | 6 votes |
export async function getSettingsContents(settingsPath: string): Promise<IWTSettings> {
const pathExists = await promisify(exists)(settingsPath);
if (!pathExists) {
throw Error('Expected settings file does not exist: ' + settingsPath);
}
const rawString = (await promisify(readFile)(settingsPath))?.toString();
if (!rawString) {
throw Error('Could not read settings file');
}
return jsoncParser.parse(rawString) as IWTSettings;
}
Example #18
Source File: global-vars.ts From language-tools with MIT License | 6 votes |
private updateForFile(filename: string) {
// Inside a small timeout because it seems chikidar is "too fast"
// and reading the file will then return empty content
setTimeout(() => {
readFile(filename, 'utf-8', (error, contents) => {
if (error) {
return;
}
const globalVarsForFile = contents
.split('\n')
.map((line) => line.match(varRegex))
.filter(isNotNullOrUndefined)
.map((line) => ({ filename, name: line[1], value: line[2] }));
this.globalVars.set(filename, globalVarsForFile);
});
}, 1000);
}
Example #19
Source File: router.ts From discord-statuspage-v2 with MIT License | 6 votes |
router = {
checkRoute (url: string, _req: IncomingMessage, res: ServerResponse) {
switch (url) {
case ('/'): {
readFile('build/web/pages/index.html', (err: Error, data: Buffer) => {
if (err) throw err
res.end(data)
})
break
}
case ('/authorized'): {
readFile('build/web/pages/authorized.html', (err: Error, data: Buffer) => {
if (err) throw err
res.end(data)
})
break
}
case ('/login'): {
readFile('build/web/pages/login.html', (err: Error, data: Buffer) => {
if (err) throw err
res.end(data)
})
break
}
case ('/error'): {
readFile('build/web/pages/error.html', (err: Error, data: Buffer) => {
if (err) throw err
res.end(data)
})
break
}
default: {
res.end('An error occurred.')
}
}
}
}
Example #20
Source File: system-font-manager.ts From open-design-sdk with Apache License 2.0 | 5 votes |
readFilePromised = promisify(readFile)
Example #21
Source File: streamingDelegate.ts From homebridge-eufy-security with Apache License 2.0 | 5 votes |
readFileAsync = promisify(readFile)
Example #22
Source File: create-rss.ts From blog with GNU General Public License v3.0 | 5 votes |
readFileAsync = promisify(readFile)
Example #23
Source File: posts.ts From blog with GNU General Public License v3.0 | 5 votes |
readFileAsync = promisify(readFile)
Example #24
Source File: deploy.ts From squid with GNU General Public License v3.0 | 5 votes |
readFileAsync = promisify(readFile)
Example #25
Source File: NoteParser.ts From vscode-markdown-notes with GNU General Public License v3.0 | 5 votes |
static async parsedFilesForWorkspace(useCache = false): Promise<Array<Note>> {
let files = await NoteWorkspace.noteFiles();
let parsedFiles = files.map((f) => NoteParser.parsedFileFor(f.fsPath));
return (await Promise.all(parsedFiles.map((note) => note.readFile(useCache)))).map((note) => {
note.parseData(useCache);
return note;
});
}
Example #26
Source File: file.ts From hubble-contracts with MIT License | 5 votes |
readFileAsync = promisify(readFile)
Example #27
Source File: edit.ts From ironfish with Mozilla Public License 2.0 | 5 votes |
readFileAsync = promisify(readFile)
Example #28
Source File: config.ts From engine with MIT License | 5 votes |
pReadFile = promisify(readFile)
Example #29
Source File: config.ts From engine with MIT License | 5 votes |
pReadFile = promisify(readFile)