fs-extra#ReadStream TypeScript Examples

The following examples show how to use fs-extra#ReadStream. 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: dbs.abstract.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
/**
     * Executes cypher against a given dbms
     * @param   dbmsId
     * @param   from
     * @param   args
     */
    abstract exec(
        dbmsId: string,
        from: string | ReadStream,
        args: {database: string; user: string; accessToken: string},
    ): Promise<string>;
Example #2
Source File: dbs.local.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
async exec(
        nameOrId: string,
        from: string | ReadStream,
        args: {
            database: string;
            user: string;
            accessToken: string;
        },
    ): Promise<string> {
        const dbms = await this.environment.dbmss.get(nameOrId);
        const params = [
            '--format=plain',
            `--address=${dbms.connectionUri}`,
            ...Object.entries(args).map(([key, val]) => {
                return key === 'accessToken' ? `--password=${val}` : `--${key}=${val}`;
            }),
        ];
        const result = await cypherShellCmd(await this.resolveDbmsRootPath(dbms.id), params, from);

        return result;
    }
Example #3
Source File: spawn-promise.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
spawnPromise = (
    command: string,
    args: string[] = [],
    options: SpawnOptionsWithoutStdio = {},
    stream: ReadStream | Transform | undefined = undefined,
): Promise<string> => {
    return new Promise((resolve, reject) => {
        let commandEscaped = command;
        let argsEscaped = args;
        if (process.platform === 'win32') {
            // https://nodejs.org/api/child_process.html#child_process_spawning_bat_and_cmd_files_on_windows
            commandEscaped = `"${command}"`;
            argsEscaped = args.map((arg) => `"${arg}"`);
            options.shell = true;
        }

        const child = spawn(commandEscaped, argsEscaped, options);

        if (stream) {
            stream.pipe(child.stdin);
        }

        const data: string[] = [];
        const collect = (chunk: Buffer): void => {
            data.push(chunk.toString());
        };

        child.stderr.on('data', collect);
        child.stderr.on('error', reject);
        child.stderr.on('close', () => resolve(data.join('')));
        child.stderr.on('end', () => resolve(data.join('')));

        child.stdout.on('data', collect);
        child.stdout.on('error', reject);
        child.stdout.on('close', () => resolve(data.join('')));
        child.stdout.on('end', () => resolve(data.join('')));
    });
}
Example #4
Source File: skynet.ts    From ass with ISC License 6 votes vote down vote up
export function SkynetDownload(fileData: FileData): Promise<ReadStream> {
	return new Promise((resolve: Function, reject) =>
		fs.ensureDir(path('share', '.skynet'))
			.then(async () => {
				await Skynet.downloadFile(getFullPath(fileData), fileData.randomId);
				return fs.createReadStream(getFullPath(fileData))
			})
			.then((stream) => resolve(stream))
			.catch(reject));
}
Example #5
Source File: cypher-shell.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
export async function cypherShellCmd(
    dbmsRootPath: string,
    args: string[],
    from: string | ReadStream,
    credentials?: string,
): Promise<string> {
    const cypherShellBinPath = path.join(dbmsRootPath, NEO4J_BIN_DIR, CYPHER_SHELL_BIN_FILE);
    const {version: dbmsVersion} = await getDistributionVersion(dbmsRootPath);
    const relateJavaHome = await resolveRelateJavaHome(dbmsVersion);

    let stream;
    if (typeof from === 'string') {
        const file = path.resolve(from);
        try {
            await fse.ensureFile(file);
        } catch (e) {
            throw new NotFoundError(`File not found (${file})`);
        }
        stream = fse.createReadStream(file);
    } else {
        stream = from;
    }

    stream = stream.pipe(appendSemicolon());

    await fse.access(cypherShellBinPath, fse.constants.X_OK).catch(() => {
        throw new NotFoundError(`No DBMS found at "${dbmsRootPath}"`);
    });

    if (args[0] === 'help' || args[0] === 'version') {
        args[0] = `--${args[0]}`;
    }

    if (credentials) {
        args.push(process.platform === 'win32' ? `--password="${credentials}"` : `--password=${credentials}`);
    }

    const env = new EnvVars({cloneFromProcess: true});
    env.set('JAVA_HOME', relateJavaHome || process.env.JAVA_HOME);
    // relateJavaHome is prepended to the PATH in order to take
    // precedence over any user installed JAVA executable.
    env.set('PATH', relateJavaHome ? `${relateJavaHome}${path.delimiter}${process.env.PATH}` : process.env.PATH);

    const output = await spawnPromise(
        cypherShellBinPath,
        args,
        {
            env: env.toObject(),
        },
        stream,
    );

    if (output.includes('ERROR: Unable to find Java executable.')) {
        throw new DependencyError('Unable to find Java executable');
    }

    if (output.includes('Neo4j cannot be started using java version')) {
        throw new DependencyError(output);
    }

    return output;
}
Example #6
Source File: awsS3.test.ts    From backstage with Apache License 2.0 4 votes vote down vote up
jest.mock('aws-sdk', () => {
  const { StorageFilesMock } = require('../../testUtils/StorageFilesMock');
  const storage = new StorageFilesMock();

  return {
    __esModule: true,
    Credentials: jest.requireActual('aws-sdk').Credentials,
    default: {
      S3: class {
        constructor() {
          storage.emptyFiles();
        }

        headObject({ Key }: { Key: string }) {
          return {
            promise: async () => {
              if (!storage.fileExists(Key)) {
                throw new Error('File does not exist');
              }
            },
          };
        }

        getObject({ Key }: { Key: string }) {
          return {
            promise: async () => storage.fileExists(Key),
            createReadStream: () => {
              const emitter = new EventEmitter();
              process.nextTick(() => {
                if (storage.fileExists(Key)) {
                  emitter.emit('data', Buffer.from(storage.readFile(Key)));
                  emitter.emit('end');
                } else {
                  emitter.emit(
                    'error',
                    new Error(`The file ${Key} does not exist!`),
                  );
                }
              });
              return emitter;
            },
          };
        }

        headBucket({ Bucket }: { Bucket: string }) {
          return {
            promise: async () => {
              if (Bucket === 'errorBucket') {
                throw new Error('Bucket does not exist');
              }
              return {};
            },
          };
        }

        upload({ Key, Body }: { Key: string; Body: ReadStream }) {
          return {
            promise: () =>
              new Promise(async resolve => {
                const chunks = new Array<Buffer>();
                Body.on('data', chunk => {
                  chunks.push(chunk as Buffer);
                });
                Body.once('end', () => {
                  storage.writeFile(Key, Buffer.concat(chunks));
                  resolve(null);
                });
              }),
          };
        }

        listObjectsV2({ Bucket }: { Bucket: string }) {
          return {
            promise: () => {
              if (
                Bucket === 'delete_stale_files_success' ||
                Bucket === 'delete_stale_files_error'
              ) {
                return Promise.resolve({
                  Contents: [{ Key: 'stale_file.png' }],
                });
              }
              return Promise.resolve({});
            },
          };
        }

        deleteObject({ Bucket }: { Bucket: string }) {
          return {
            promise: () => {
              if (Bucket === 'delete_stale_files_error') {
                throw new Error('Message');
              }
              return Promise.resolve();
            },
          };
        }
      },
    },
  };
});