Unable to create observable from Observable.bindNodeCallback (fs.readFile) in TypeScript

I am trying to use rxjs 5 to write a Node.js server in TypeScript, but I hit an error while converting fs.readFileto its rxjs form. I expect the following code to work in TypeScript

// This is a JavaScript example from the official documentation. It should
// also work at the TypeScript envrionment.

import * as fs from 'fs';
import { Observable } from 'rxjs';

let readFileAsObservable = Observable.bindNodeCallback(fs.readFile);

// This is the line that throws the error.
let result = readFileAsObservable('./roadNames.txt', 'utf8');

result.subscribe(x => console.log(x), e => console.error(e));

However, my editor reports a TypeScript error when I add a second parameter 'utf-8'

Supplied parameters do not match any signature of call target.

I am trying to find a usage guide fs.readFile()in rxjs and TypeScript, but not much luck.

+6
source share
2 answers

bindCallbackand bindNodeCallbackcan be complicated with TypeScript, since it all depends on how TypeScript indicates the parameters of the function.

, , , , , : . , :

const n: number = Observable.bindNodeCallback(fs.readFile);

:

Type '(v1: string) => Observable<Buffer>' is not assignable to type 'number'.

, , TypeScript readFile.

, , . , :

const n: number = Observable.bindNodeCallback((
  path: string,
  encoding: string,
  callback: (error: Error, buffer: Buffer) => void
) => fs.readFile(path, encoding, callback));

:

Type '(v1: string, v2: string) => Observable<Buffer>' is not assignable to type 'number'.

, :

let readFileAsObservable = Observable.bindNodeCallback((
  path: string,
  encoding: string,
  callback: (error: Error, buffer: Buffer) => void
) => fs.readFile(path, encoding, callback));

let result = readFileAsObservable('./package.json', 'utf8');
result.subscribe(
  buffer => console.log(buffer.toString()),
  error => console.error(error)
);
+9

, , , .

(<Function>Rx.Observable.bindNodeCallback(fs.readFile))('./file.txt', 'utf8').subscribe();
+1

Source: https://habr.com/ru/post/1016594/


All Articles