fs-extra#readFile TypeScript Examples

The following examples show how to use fs-extra#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: Sticker.ts    From wa-sticker-formatter with MIT License 6 votes vote down vote up
private _parse = async (): Promise<Buffer> =>
        Buffer.isBuffer(this.data)
            ? this.data
            : this.data.trim().startsWith('<svg')
            ? Buffer.from(this.data)
            : (async () =>
                  existsSync(this.data)
                      ? readFile(this.data)
                      : axios.get(this.data as string, { responseType: 'arraybuffer' }).then(({ data }) => data))()
Example #2
Source File: setupTestEnv.ts    From joplin-utils with MIT License 6 votes vote down vote up
export async function setupTestEnv() {
  config.baseUrl = 'http://localhost:27583'
  const envPath = path.resolve(__dirname, '.env.local')
  if (!(await pathExists(envPath))) {
    throw new Error('请更新 .env.local 文件:' + envPath)
  }
  const env = await readFile(envPath, 'utf8')
  config.token = parse(env).TOKEN!
}
Example #3
Source File: createEmptyFile.test.ts    From joplin-utils with MIT License 6 votes vote down vote up
describe('测试 createEmptyFile', () => {
  const tempPath = path.resolve(__dirname, '.temp')
  beforeEach(async () => {
    await remove(tempPath)
    await mkdirp(tempPath)
  })
  it.skip('基本示例', async () => {
    const filePath = path.resolve(tempPath, 'test.drawio.svg')
    let handle: number
    try {
      handle = await createEmptyFile(filePath)
      expect(await readFile(filePath, 'utf-8')).toBe('')
    } finally {
      await close(handle!)
    }
  })
})
Example #4
Source File: Importer.ts    From joplin-utils with MIT License 6 votes vote down vote up
async listNote(noteList: Omit<ExportNote, 'body'>[]): Promise<ExportNote[]> {
    return await AsyncArray.map(noteList, async (item) => {
      const notePath = path.resolve(
        this.config.rootPath,
        'notes',
        item.filePath,
      )
      return {
        ...item,
        body: await readFile(notePath, 'utf-8'),
      } as ExportNote
    })
  }
Example #5
Source File: setupTestEnv.ts    From joplin-utils with MIT License 6 votes vote down vote up
export async function setupTestEnv() {
  config.baseUrl = 'http://localhost:27583'
  const envPath = path.resolve(__dirname, '.env.local')
  if (!(await pathExists(envPath))) {
    throw new Error('请更新 .env.local 文件:' + envPath)
  }
  const env = await readFile(envPath, 'utf8')
  config.token = parse(env).TOKEN!
}
Example #6
Source File: index.ts    From ng-icons with MIT License 6 votes vote down vote up
async function loadIconset(iconset: Iconset): Promise<Record<string, string>> {
  // load all the svg iconDetails within the path
  const iconPaths = sync(iconset.glob);

  if (iconPaths.length === 0) {
    throw new Error('No icons found for iconset: ' + iconset.glob);
  }

  console.log('Found ' + iconPaths.length + ' icons in ' + iconset.glob);

  // read the contents of each file
  const output: Record<string, string> = {};

  for (const iconPath of iconPaths) {
    const iconName = iconset.getIconName(
      names(basename(iconPath, '.svg')).className,
      iconPath,
    );
    let svg = await readFile(iconPath, 'utf8');
    svg = await optimizeIcon(svg, iconset.svg);
    output[iconName] = svg;

    iconList.add(iconName);
  }

  iconCount += iconPaths.length;

  return output;
}
Example #7
Source File: read-properties-file.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
export async function readPropertiesFile(path: string): Promise<PropertyEntries> {
    const conf = await readFile(path, 'utf8');
    const lines = map(split(conf, NEW_LINE), trim);

    return map(lines, (line): [string, string] => {
        const [key, ...rest] = split(line, PROPERTIES_SEPARATOR);

        return [key, join(rest, PROPERTIES_SEPARATOR)];
    });
}
Example #8
Source File: npm.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
async publish(publishedDirectory: string, packageJson: {}, dry: boolean, log: Logger): Promise<void> {
    const readme = await readFile(joinPaths(publishedDirectory, "README.md"));

    return new Promise<void>((resolve, reject) => {
      const body = createTgz(publishedDirectory, reject);
      const metadata = { readme, ...packageJson };
      if (dry) {
        log(`(dry) Skip publish of ${publishedDirectory} to ${this.registry}`);
      }
      resolve(
        dry
          ? undefined
          : promisifyVoid((cb) => {
              this.client.publish(
                this.registry,
                {
                  access: "public",
                  auth: this.auth,
                  metadata: metadata as NeedToFixNpmRegistryClientTypings,
                  body: body as NeedToFixNpmRegistryClientTypings,
                },
                cb
              );
            })
      );
    });
  }
Example #9
Source File: util.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
export async function readJson(path: string) {
  const text = await readFile(path, "utf-8");
  return JSON.parse(stripJsonComments(text));
}
Example #10
Source File: AppUpdater.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
private async getOrCreateStagingUserId(): Promise<string> {
    const file = path.join(this.app.userDataPath, ".updaterId");
    try {
      const id = await readFile(file, "utf-8");
      if (UUID.check(id)) {
        return id;
      } else {
        this._logger.warn(
          `Staging user id file exists, but content was invalid: ${id}`
        );
      }
    } catch (e) {
      if (e.code !== "ENOENT") {
        this._logger.warn(
          `Couldn't read staging user ID, creating a blank one: ${e}`
        );
      }
    }

    const id = UUID.v5(randomBytes(4096), UUID.OID);
    this._logger.info(`Generated new staging user ID: ${id}`);
    try {
      await outputFile(file, id);
    } catch (e) {
      this._logger.warn(`Couldn't write out staging user ID: ${e}`);
    }
    return id;
  }
Example #11
Source File: to-node.ts    From mordred with MIT License 6 votes vote down vote up
export async function fileToNode(filename: string, cwd: string, getType: typeof GetType): Promise<FileNode> {
  const absolutePath = join(cwd, filename)
  const content = await readFile(absolutePath, 'utf8')
  const { ctime, mtime } = await stat(absolutePath)
  return {
    id: getFileNodeId(filename),
    type: FILE_NODE_TYPE,
    mime: getType(extname(filename)),
    createdAt: ctime,
    updatedAt: mtime,    
    content,
    relativePath: filename,
    absolutePath,
    slug: filename.replace(/\.[a-zA-Z0-9]+$/, '')
  }
}
Example #12
Source File: html-view.ts    From malagu with MIT License 6 votes vote down vote up
async render(model: any, { metadata }: ViewMetadata): Promise<void> {
        const response = Context.getCurrent().response;
        const { baseViewDir, cache } = this.options;
        const template = await readFile(join(__dirname, baseViewDir, metadata!.file), { encoding: 'utf8' });
        if (cache) {
            parse(template);
        }
        response.body = render(template, model);
    }
Example #13
Source File: crop.ts    From wa-sticker-formatter with MIT License 6 votes vote down vote up
crop = async (filename: string): Promise<Buffer> => {
    const file = await new Promise<string>((resolve) => {
        const name = `${tmpdir()}/${Math.random().toString(36)}.webp`
        Ffmpeg(filename)
            // eslint-disable-next-line no-useless-escape
            .outputOptions([
                '-vcodec',
                'libwebp',
                '-vf',
                // eslint-disable-next-line no-useless-escape
                `crop=w='min(min(iw\,ih)\,500)':h='min(min(iw\,ih)\,500)',scale=500:500,setsar=1,fps=15`,
                '-loop',
                '0',
                '-preset',
                'default',
                '-an',
                '-vsync',
                '0',
                '-s',
                '512:512'
            ])
            .save(name)
            .on('end', () => resolve(name))
    })
    return await readFile(file)
}
Example #14
Source File: install-manager.ts    From malagu with MIT License 6 votes vote down vote up
async render(): Promise<void> {
        const pkg = require('../../package.json');
        const packageJsonPath = resolve(this.outputDir, 'package.json');
        let packageContent = await readFile(packageJsonPath, { encoding: 'utf8' });
        packageContent = packageContent.replace(/{{ version }}/g, pkg.version);
        if (this.opts.forceInstallingComponent) {
            const runtimePkg = JSON.parse(packageContent);
            if (runtimePkg.malagu?.components || runtimePkg.malagu?.devComponents) {
                const { components, devComponents } = runtimePkg.malagu;
                runtimePkg.dependencies = { ...runtimePkg.dependencies, ...components };
                runtimePkg.devDependencies = { ...runtimePkg.devDependencies, ...devComponents };
                packageContent = JSON.stringify(runtimePkg, undefined, 2);
            }
        }
        await writeFile(packageJsonPath, packageContent);
    }
Example #15
Source File: imagesToWebp.ts    From wa-sticker-formatter with MIT License 6 votes vote down vote up
imagesToWebp = async (filename: string): Promise<Buffer> => {
    const file = await new Promise<string>((resolve) => {
        const name = `${tmpdir()}/${Math.random().toString(36)}.webp`
        Ffmpeg(filename)
            .outputOption('-lavfi split[v],palettegen,[v]paletteuse')
            .outputOption('-vcodec libwebp')
            .outputFPS(10)
            .loop(0)
            .save(name)
            .on('end', () => resolve(name))
    })
    return await readFile(file)
}
Example #16
Source File: videoToGif.ts    From wa-sticker-formatter with MIT License 6 votes vote down vote up
videoToGif = async (data: Buffer): Promise<Buffer> => {
    const filename = `${tmpdir()}/${Math.random().toString(36)}`
    const [video, gif] = ['video', 'gif'].map((ext) => `${filename}.${ext}`)
    await writeFile(video, data)
    await new Promise((resolve) => {
        ffmpeg(video).save(gif).on('end', resolve)
    })
    const buffer = await readFile(gif)
    ;[video, gif].forEach((file) => unlink(file))
    return buffer
}
Example #17
Source File: TestProject.ts    From yarn-plugins with MIT License 6 votes vote down vote up
public static async setup(): Promise<TestProject> {
    const dir = await tmp.dir();
    const pluginBundles = await globby('packages/*/bundles/**/*.js', {
      cwd: PROJECT_DIR,
    });
    const plugins = pluginBundles.map((src) => ({
      src,
      name: '@yarnpkg/' + basename(src, extname(src)),
      dest: posix.join('.yarn', 'plugins', ...src.split(sep).slice(3)),
    }));

    for (const path of plugins) {
      await copy(join(PROJECT_DIR, path.src), join(dir.path, path.dest));
    }

    const yarnConfig = safeLoad(
      await readFile(join(PROJECT_DIR, '.yarnrc.yml'), 'utf8'),
    ) as Record<string, unknown>;

    // Create .yarnrc.yml
    await outputFile(
      join(dir.path, '.yarnrc.yml'),
      safeDump({
        yarnPath: join(PROJECT_DIR, yarnConfig.yarnPath as string),
        plugins: plugins.map((plugin) => ({
          path: plugin.dest,
          spec: plugin.name,
        })),
      }),
    );

    // Create package.json
    await outputJSON(join(dir.path, 'package.json'), {
      private: true,
      workspaces: ['packages/*'],
    });

    return new TestProject(dir);
  }
Example #18
Source File: dev.ts    From gdmod with MIT License 6 votes vote down vote up
async function buildMod() {
  const zip = new JSZip();

  // Copy resources
  await Promise.all(
    (
      await readdir("./resources")
    ).map(async (file) =>
      zip.file("resources/" + file, await readFile("./resources/" + file))
    )
  );

  // Read manifests
  const [gdmod, resources, bundle] = await Promise.all([
    await readFile("./data/GDMod.json"),
    await readFile("./data/resources.json"),
    await readFile("./dist/bundle.js"),
  ]);

  return new Promise(async (resolve, reject) =>
    zip
      .file("data/GDMod.json", gdmod)
      .file("data/resources.json", resources)
      .file("data/includes.json", `["bundle.js"]`)
      .file("code/bundle.js", bundle)
      .generateNodeStream()
      .pipe(createWriteStream("./dist/mod.zip"))
      .once("finish", resolve)
      .once("error", reject)
  );
}
Example #19
Source File: manifest-handling.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
async function readFlexEnabledFlagFromManifestFile(
  manifestUri: string
): Promise<boolean | "INVALID"> {
  const manifestContent = await readFile(
    URI.parse(manifestUri).fsPath,
    "utf-8"
  );

  let manifestJsonObject;
  try {
    manifestJsonObject = JSON.parse(manifestContent);
  } catch (err) {
    return "INVALID";
  }

  const ui5Object = manifestJsonObject["sap.ui5"] ?? { flexEnabled: false };
  const isFlexEnabled = ui5Object.flexEnabled;

  return isFlexEnabled;
}
Example #20
Source File: detector-filesystem.ts    From malagu with MIT License 5 votes vote down vote up
public readFile = async (name: string): Promise<Buffer> => {
        let p = this.readFileCache.get(name);
        if (!p) {
            p = this.doReadFile(name);
            this.readFileCache.set(name, p);
        }
        return p;
    };
Example #21
Source File: Controller.ts    From vscode-alxmldocumentation with MIT License 5 votes vote down vote up
/**
     * Initialize AL XML Documentation.
     */
    public async Initialize() {
        try 
        {
            await window.withProgress({
                location: ProgressLocation.Window,
                title: 'AL XML Documentation initialization in progress...',
            }, async (progress, token) => {
                let workspacePaths = workspace.workspaceFolders;
                if ((!workspacePaths) || (workspacePaths === undefined)) {
                    throw new Error('Workspace folders could not be retrieved.');
                }
    
                for (let validPath of workspacePaths) {
                    let allFiles = await workspace.findFiles(new RelativePattern(validPath, '**/*.al'), undefined, undefined, token);
                    let relevantFileTasks = allFiles.map(async (file: Uri) => {
                        let content = await readFile(file.fsPath, 'utf-8');
                        if (content.match(/(procedure|trigger|event)\s+(.*?)\(/gm)) {
                            return { uri: file, content: content };
                        }
    
                        return undefined;
                    });
                    let relevantFiles = await Promise.all(relevantFileTasks);
                    relevantFiles = relevantFiles.filter(f => f);
    
                    let tasks: Array<Promise<void>> = [];
                    let task = async (file: { uri: Uri, content: string }) => {
                        let document = Object.assign({});
                        document.getText = () => file.content;
                        document.fileName = file.uri.fsPath;
                        document.uri = file.uri;
                        
                        ALSyntaxUtil.GetALObject(document as any);
                    };
                    let max = relevantFiles.length;
                    for (let i = 0; i < max; i++) {
                        let file = relevantFiles[i];
                        tasks.push(task(file!));
    
                        if (i % 500 === 0) {
                            await Promise.all(tasks);
                            tasks = [];
                        }
                    }
    
                    if (tasks.length > 0) {
                        await Promise.all(tasks);
                    }
                }
    
                return true;
            });
        }
        catch (ex)
        {
            console.debug(ex);
        }
    }
Example #22
Source File: JoplinNoteCommandService.ts    From joplin-utils with MIT License 5 votes vote down vote up
async init(appConfig: AppConfig) {
    if (!appConfig.token) {
      return
    }
    config.token = appConfig.token
    config.baseUrl = appConfig.baseUrl

    setInterval(async () => {
      await this.config.noteViewProvider.refresh()
    }, 1000 * 10)
    const tempNoteDirPath = path.resolve(GlobalContext.context.globalStorageUri.fsPath, '.tempNote')
    const tempResourceDirPath = path.resolve(GlobalContext.context.globalStorageUri.fsPath, '.tempResource')
    await AsyncArray.forEach([tempNoteDirPath, tempResourceDirPath], async (path) => {
      // await remove(path)
      await mkdirp(path)
    })
    watch(tempNoteDirPath)
      .on('change', async (filePath) => {
        const id = GlobalContext.openNoteMap.get(filePath)
        if (!id) {
          return
        }
        const content = await readFile(filePath, 'utf-8')
        const { title, body } = JoplinNoteUtil.splitTitleBody(content)
        const newNote = { id, body } as NoteProperties
        if (title) {
          newNote.title = title.startsWith('# ') ? title.substring(2) : title
        }
        await noteApi.update(newNote)
        this.config.noteViewProvider.fire()
        const resourceList = await noteApi.resourcesById(id)
        GlobalContext.openNoteResourceMap.set(id, resourceList)
      })
      .on('error', (err) => {
        logger.error('watch note error', err)
      })
    watch(tempResourceDirPath)
      .on('change', async (filePath) => {
        const id = GlobalContext.openResourceMap.get(filePath)
        if (!id) {
          return
        }
        await resourceApi.update({
          id,
          // title: path.basename(filePath),
          data: createReadStream(filePath),
        })
      })
      .on('error', (err) => {
        logger.error('watch resource error', err)
      })
  }
Example #23
Source File: index.ts    From cli with MIT License 5 votes vote down vote up
private async makeZip(sourceDirection: string, targetFileName: string) {
    let ignore = [];
    if (this.core.service?.experimentalFeatures?.removeUselessFiles) {
      this.core.cli.log(' - Experimental Feature RemoveUselessFiles');
      ignore = uselessFilesMatch;
    }
    const globbyMatched = ['**'];
    const npmClient = this.getNPMClient();
    if (npmClient?.startsWith('pnpm')) {
      globbyMatched.push('**/.pnpm/**');
    }
    const fileList = await globby(globbyMatched, {
      onlyFiles: false,
      followSymbolicLinks: false,
      cwd: sourceDirection,
      ignore,
    });
    const zip = new JSZip();
    const isWindows = platform() === 'win32';
    for (const fileName of fileList) {
      const absPath = join(sourceDirection, fileName);
      const stats = await lstat(absPath);
      if (stats.isDirectory()) {
        zip.folder(fileName);
      } else if (stats.isSymbolicLink()) {
        let link = await readlink(absPath);
        if (isWindows) {
          link = relative(dirname(absPath), link).replace(/\\/g, '/');
        }
        zip.file(fileName, link, {
          binary: false,
          createFolders: true,
          unixPermissions: stats.mode,
        });
      } else if (stats.isFile()) {
        const fileData = await readFile(absPath);
        zip.file(fileName, fileData, {
          binary: true,
          createFolders: true,
          unixPermissions: stats.mode,
        });
      }
    }
    await new Promise((res, rej) => {
      zip
        .generateNodeStream({
          platform: 'UNIX',
          compression: 'DEFLATE',
          compressionOptions: {
            level: 6,
          },
        })
        .pipe(createWriteStream(targetFileName))
        .once('finish', res)
        .once('error', rej);
    });
  }
Example #24
Source File: index.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
async function runTests(
  dirPath: string,
  onlyTestTsNext: boolean,
  expectOnly: boolean,
  tsLocal: string | undefined
): Promise<void> {
  const isOlderVersion = /^v(0\.)?\d+$/.test(basename(dirPath));

  const indexText = await readFile(joinPaths(dirPath, "index.d.ts"), "utf-8");
  // If this *is* on DefinitelyTyped, types-publisher will fail if it can't parse the header.
  const dt = indexText.includes("// Type definitions for");
  if (dt) {
    // Someone may have copied text from DefinitelyTyped to their type definition and included a header,
    // so assert that we're really on DefinitelyTyped.
    const dtRoot = findDTRoot(dirPath);
    const packageName = basename(dirPath);
    assertPathIsInDefinitelyTyped(dirPath, dtRoot);
    assertPathIsNotBanned(packageName);
    assertPackageIsNotDeprecated(packageName, await readFile(joinPaths(dtRoot, "notNeededPackages.json"), "utf-8"));
  }

  const typesVersions = await mapDefinedAsync(await readdir(dirPath), async (name) => {
    if (name === "tsconfig.json" || name === "tslint.json" || name === "tsutils") {
      return undefined;
    }
    const version = withoutPrefix(name, "ts");
    if (version === undefined || !(await stat(joinPaths(dirPath, name))).isDirectory()) {
      return undefined;
    }

    if (!TypeScriptVersion.isTypeScriptVersion(version)) {
      throw new Error(`There is an entry named ${name}, but ${version} is not a valid TypeScript version.`);
    }
    if (!TypeScriptVersion.isRedirectable(version)) {
      throw new Error(`At ${dirPath}/${name}: TypeScript version directories only available starting with ts3.1.`);
    }
    return version;
  });

  if (dt) {
    await checkPackageJson(dirPath, typesVersions);
  }

  const minVersion = maxVersion(
    getMinimumTypeScriptVersionFromComment(indexText),
    TypeScriptVersion.lowest
  ) as TypeScriptVersion;
  if (onlyTestTsNext || tsLocal) {
    const tsVersion = tsLocal ? "local" : TypeScriptVersion.latest;
    await testTypesVersion(dirPath, tsVersion, tsVersion, isOlderVersion, dt, expectOnly, tsLocal, /*isLatest*/ true);
  } else {
    // For example, typesVersions of [3.2, 3.5, 3.6] will have
    // associated ts3.2, ts3.5, ts3.6 directories, for
    // <=3.2, <=3.5, <=3.6 respectively; the root level is for 3.7 and above.
    // so this code needs to generate ranges [lowest-3.2, 3.3-3.5, 3.6-3.6, 3.7-latest]
    const lows = [TypeScriptVersion.lowest, ...typesVersions.map(next)];
    const his = [...typesVersions, TypeScriptVersion.latest];
    assert.strictEqual(lows.length, his.length);
    for (let i = 0; i < lows.length; i++) {
      const low = maxVersion(minVersion, lows[i]);
      const hi = his[i];
      assert(
        parseFloat(hi) >= parseFloat(low),
        `'// Minimum TypeScript Version: ${minVersion}' in header skips ts${hi} folder.`
      );
      const isLatest = hi === TypeScriptVersion.latest;
      const versionPath = isLatest ? dirPath : joinPaths(dirPath, `ts${hi}`);
      if (lows.length > 1) {
        console.log("testing from", low, "to", hi, "in", versionPath);
      }
      await testTypesVersion(versionPath, low, hi, isOlderVersion, dt, expectOnly, undefined, isLatest);
    }
  }
}
Example #25
Source File: yarn.ts    From malagu with MIT License 5 votes vote down vote up
readLockfile(lockfilePath: string) {
        return readFile(lockfilePath, 'utf8');
    }
Example #26
Source File: AppUpdater.ts    From electron-differential-updater with MIT License 5 votes vote down vote up
private async loadUpdateConfig(): Promise<any> {
    if (this._appUpdateConfigPath == null) {
      this._appUpdateConfigPath = this.app.appUpdateConfigPath;
    }
    return safeLoad(await readFile(this._appUpdateConfigPath, "utf-8"));
  }
Example #27
Source File: deploy.ts    From malagu with MIT License 5 votes vote down vote up
async function createOrUpdateCustomDomain(customDomain: any, qualifier: string, params: api.Params) {
    const { name, protocol, certConfig, routeConfig } = customDomain;
    let domainName = name;
    const opts: any = {
        protocol
    };

    if (domainName === 'auto') {
        await SpinnerUtil.start('Generated custom domain', async () => {
            domainName = await genDomain(params);
        });
    }

    if (certConfig?.certName) {
        opts.certConfig = { ...certConfig };
        const privateKey = certConfig.privateKey;
        const certificate = certConfig.certificate;

        if (privateKey?.endsWith('.key')) {
            opts.certConfig.privateKey = await readFile(privateKey, 'utf-8');
        }
        if (certificate?.endsWith('.pem')) {
            opts.certConfig.certificate = await readFile(certificate, 'utf-8');
        }
    }

    if (routeConfig) {
        opts.routeConfig = routeConfig;
    }
    const customDomainInfo = await getCustomDomain(fcClient, domainName);
    if (customDomainInfo) {
        const { data } = customDomainInfo;
        const routes: any[] = [];
        if (data?.routeConfig?.routes) {
            for (const route of data.routeConfig.routes) {
                const target = opts.routeConfig.routes.find((r: any) => r.path === route.path);
                if (target) {
                    routes.push({ ...route, ...target });
                    opts.routeConfig.routes.splice(opts.routeConfig.routes.findIndex((r: any) => r.path === target.path), 1);
                } else {
                    routes.push(route);
                }
            }
            opts.routeConfig.routes = [...opts.routeConfig.routes, ...routes];
        }
        await SpinnerUtil.start(`Update ${domainName} custom domain`, async () => {
            await fcClient.updateCustomDomain(domainName, opts);
        });
    } else {
        opts.domainName = domainName;
        await SpinnerUtil.start(`Create ${domainName} custom domain`, async () => {
            retry(async () => {
                await fcClient.createCustomDomain(domainName, opts);
            }, 1000, 5)
        });
    }
    let path = '';
    if (opts.routeConfig?.routes?.length) {
        for (const route of opts.routeConfig.routes) {
            if (route.qualifier === qualifier) {
                path = route.path?.split('*')[0] || '';
            }
        }
    }
    console.log(chalk`    - Url: ${chalk.green.bold(
        `${protocol.includes('HTTPS') ? 'https' : 'http'}://${domainName}${path}`)}`);
}
Example #28
Source File: detector-filesystem.ts    From malagu with MIT License 5 votes vote down vote up
protected doReadFile(name: string): Promise<Buffer> {
        return readFile(resolve(this.projectPath, name));
    }
Example #29
Source File: index.test.ts    From cli with MIT License 4 votes vote down vote up
describe('/test/index.test.ts', () => {
  it('use custom artifact directory', async () => {
    const baseDir = join(__dirname, './fixtures/base-fc');
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      commands: ['package'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      log: console,
    });
    core.addPlugin(PackagePlugin);
    core.addPlugin(AliyunFCPlugin);
    await core.ready();
    await core.invoke(['package']);
    const buildPath = join(baseDir, '.serverless');
    assert(existsSync(join(buildPath, 'dist/index.js')));
    assert(existsSync(join(buildPath, 'node_modules')));
    assert(existsSync(join(buildPath, 'src')));
    assert(existsSync(join(buildPath, 'index.js')));
    assert(existsSync(join(buildPath, 'package.json')));
    assert(existsSync(join(buildPath, 'tsconfig.json')));
    assert(existsSync(join(baseDir, 'serverless.zip')));

    const zip = new JSZip();
    const zipData = await readFile(join(baseDir, 'serverless.zip'));
    const zipObj = await zip.loadAsync(zipData);
    assert(zipObj.file('f.yml'));
    assert(zipObj.file('dist/index.js'));
    assert(zipObj.file('node_modules/@midwayjs/core/package.json'));
    // clean
    await remove(join(baseDir, 'serverless.zip'));
  });

  it('use custom artifact directory', async () => {
    if (process.version.includes('v10')) {
      return;
    }
    const baseDir = join(__dirname, './fixtures/base-fc');
    process.env.SERVERLESS_DEPLOY_ID = 'test';
    process.env.SERVERLESS_DEPLOY_AK = 'test';
    process.env.SERVERLESS_DEPLOY_SECRET = 'test';
    const logs = [];
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      options: {
        skipDeploy: true,
        skipInstallDep: true,
      },
      commands: ['deploy'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      log: {
        log: (...args) => {
          logs.push(...args);
        },
      },
    });
    core.addPlugin(DeployPlugin);
    core.addPlugin(PackagePlugin);
    core.addPlugin(AliyunFCPlugin);
    await core.ready();
    await core.invoke(['deploy']);
    const logStr = logs.join('\n');
    assert(logStr.includes('success'));
    // clean
    await remove(join(baseDir, '.serverless'));
  });

  it('only build index2', async () => {
    const baseDir = join(__dirname, './fixtures/base-fc');
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      commands: ['package'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      log: console,
    });
    core.addPlugin(PackagePlugin);
    core.addPlugin(AliyunFCPlugin);
    await core.ready();
    await core.invoke(['package'], false, { function: 'index2' });
    const buildPath = join(baseDir, '.serverless');
    assert(existsSync(join(buildPath, 'dist/index.js')));
    assert(existsSync(join(buildPath, 'node_modules')));
    assert(existsSync(join(buildPath, 'src')));
    assert(existsSync(join(buildPath, 'index.js')));
    assert(existsSync(join(buildPath, 'package.json')));
    assert(existsSync(join(buildPath, 'tsconfig.json')));
    assert(existsSync(join(baseDir, 'serverless.zip')));

    const entryData = readFileSync(join(buildPath, 'index.js')).toString();
    assert(!entryData.includes('exports.handler '));
    assert(entryData.includes('exports.handler2 '));

    const zip = new JSZip();
    const zipData = await readFile(join(baseDir, 'serverless.zip'));
    const zipObj = await zip.loadAsync(zipData);
    assert(zipObj.file('f.yml'));
    assert(zipObj.file('dist/index.js'));
    assert(zipObj.file('node_modules/@midwayjs/core/package.json'));
    // clean
    await remove(join(baseDir, 'serverless.zip'));
  });

  it('build eaas function', async () => {
    const baseDir = join(__dirname, './fixtures/eaas');
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      commands: ['package'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      log: console,
    });
    core.addPlugin(PackagePlugin);
    core.addPlugin(AliyunFCPlugin);
    await core.ready();
    await core.invoke(['package']);

    const buildPath = join(baseDir, '.serverless');
    assert(existsSync(join(buildPath, 'app')));
    assert(existsSync(join(buildPath, 'node_modules')));
    assert(existsSync(join(buildPath, 'config')));
    assert(existsSync(join(buildPath, 'package.json')));
    assert(existsSync(join(buildPath, 'app.js')));
    assert(existsSync(join(buildPath, 'agent.js')));
    assert(existsSync(join(buildPath, 'index.js')));
    assert(existsSync(join(baseDir, 'serverless.zip')));

    // clean
    await remove(join(baseDir, '.serverless'));
  });
  it('build by serverless-dev', async () => {
    if (process.version.includes('v10')) {
      return;
    }
    const accessYaml = join(homedir(), '.s/access.yaml');
    const exists = existsSync(accessYaml);
    if (!exists) {
      ensureFileSync(accessYaml);
      writeFileSync(accessYaml, '');
    }

    const baseDir = join(__dirname, './fixtures/serverless-devs');
    const logs = [];
    const core = new CommandCore({
      config: {
        servicePath: baseDir,
      },
      commands: ['deploy'],
      service: loadSpec(baseDir),
      provider: 'aliyun',
      log: {
        ...console,
        log: (...logInfo) => {
          logs.push(...logInfo);
        },
      },
      options: {
        skipDeploy: true,
        skipInstallDep: true,
      },
    });
    core.addPlugin(PackagePlugin);
    core.addPlugin(DeployPlugin);
    core.addPlugin(AliyunFCPlugin);
    await core.ready();
    await core.invoke(['deploy']);
    // clean
    await remove(join(baseDir, '.serverless'));
    const logsStr = logs.join(';');
    assert(logsStr.includes('@serverless-devs'));
    assert(logsStr.includes('deploy success'));
    if (!exists) {
      await remove(accessYaml);
    }
  });
});