• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript url.parse函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中url.parse函数的典型用法代码示例。如果您正苦于以下问题:TypeScript parse函数的具体用法?TypeScript parse怎么用?TypeScript parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了parse函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: async

  const process = async (inputUrl: string, context: string, resourceCache: Map<string, string>) => {
    // If root-relative, absolute or protocol relative url, leave as is
    if (/^((?:\w+:)?\/\/|data:|chrome:|#)/.test(inputUrl)) {
      return inputUrl;
    }

    // If starts with a caret, remove and return remainder
    // this supports bypassing asset processing
    if (inputUrl.startsWith('^')) {
      return inputUrl.substr(1);
    }

    const cacheKey = path.resolve(context, inputUrl);
    const cachedUrl = resourceCache.get(cacheKey);
    if (cachedUrl) {
      return cachedUrl;
    }

    if (inputUrl.startsWith('~')) {
      inputUrl = inputUrl.substr(1);
    }

    if (inputUrl.startsWith('/')) {
      let outputUrl = '';
      if (deployUrl.match(/:\/\//) || deployUrl.startsWith('/')) {
        // If deployUrl is absolute or root relative, ignore baseHref & use deployUrl as is.
        outputUrl = `${deployUrl.replace(/\/$/, '')}${inputUrl}`;
      } else if (baseHref.match(/:\/\//)) {
        // If baseHref contains a scheme, include it as is.
        outputUrl = baseHref.replace(/\/$/, '') + dedupeSlashes(`/${deployUrl}/${inputUrl}`);
      } else {
        // Join together base-href, deploy-url and the original URL.
        outputUrl = dedupeSlashes(`/${baseHref}/${deployUrl}/${inputUrl}`);
      }

      resourceCache.set(cacheKey, outputUrl);

      return outputUrl;
    }

    const { pathname, hash, search } = url.parse(inputUrl.replace(/\\/g, '/'));
    const resolver = (file: string, base: string) => new Promise<string>((resolve, reject) => {
      loader.resolve(base, file, (err, result) => {
        if (err) {
          reject(err);

          return;
        }
        resolve(result);
      });
    });

    const result = await resolve(pathname as string, context, resolver);

    return new Promise<string>((resolve, reject) => {
      loader.fs.readFile(result, (err: Error, content: Buffer) => {
        if (err) {
          reject(err);

          return;
        }

        let outputPath = interpolateName(
          { resourcePath: result } as webpack.loader.LoaderContext,
          filename,
          { content },
        );

        if (resourcesOutputPath) {
          outputPath = path.posix.join(resourcesOutputPath, outputPath);
        }

        loader.addDependency(result);
        loader.emitFile(outputPath, content, undefined);

        let outputUrl = outputPath.replace(/\\/g, '/');
        if (hash || search) {
          outputUrl = url.format({ pathname: outputUrl, hash, search });
        }

        if (deployUrl && loader.loaders[loader.loaderIndex].options.ident !== 'extracted') {
          outputUrl = url.resolve(deployUrl, outputUrl);
        }

        resourceCache.set(cacheKey, outputUrl);
        resolve(outputUrl);
      });
    });
  };
开发者ID:DevIntent,项目名称:angular-cli,代码行数:89,代码来源:postcss-cli-resources.ts


示例2: function

dispatcher.onGet('/', function(request: any, result: any) {
  const query: any = url.parse(request.url, true).query;

  const page: number = _.isUndefined(query.page) ? 1 : query.page;
  const pageSize: number = query.pageSize;

  const start: number = (page - 1) * pageSize;
  const end: number = start + pageSize;

  let sortType: string;
  let sortBy: string;

  if (!_.isUndefined(query.orderBy)) {
    sortType = query.orderBy.indexOf('-') === 0 ? 'desc' : 'asc';
    sortBy = query.orderBy.replace('-', '');
  }

  let filters: string[] = [];
  for (let filter in query) {
    if (filter !== 'page' && filter !== 'pageSize' && filter !== 'orderBy'
        && filter !== 'expand') {
      filters[filter] = query[filter];
    }
  }

  let data: any[] = DEMO_DATA;

  // apply filters
  data = _.filter(data, function(item: any) {
    let match = true;
    for (let filter in filters) {
      if (filters.hasOwnProperty(filter)) {
        let value = _.get(item, filter).toString();

        match = match &&
          (value.match(new RegExp(filters[filter], 'i')) !== null);
      }
    }

    return match;
  });

  result.writeHead(200, {
    'Content-Type': 'text/plain',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Expose-Headers': 'X-Pagination-Total-Count, X-Pagination-Page-Count, X-Pagination-Current-Page, X-Pagination-Per-Page',
    'X-Pagination-Total-Count': data.length,
    'X-Pagination-Page-Count': Math.ceil(data.length / pageSize),
    'X-Pagination-Current-Page': page,
    'X-Pagination-Per-Page': !_.isUndefined(pageSize) ? pageSize : ''
  });

  // sort data
  if (!_.isUndefined(sortBy)) {
    data = _.orderBy(data, [sortBy], [sortType]);
  }

  // slice page
  if (!_.isUndefined(pageSize)) {
    data = data.slice(start, end);
  }

  result.end(JSON.stringify(data));
});
开发者ID:raketasoft,项目名称:ng2-grid,代码行数:64,代码来源:server.ts


示例3: function

Repo.prototype.clone_ = function(user, repo, repo_url) {
    logger.log(`Cloning ${logger.colors.green(`${user}/${repo}`)}`)
    git.clone(url.parse(repo_url).href, repo)
}
开发者ID:gamerson,项目名称:gh,代码行数:4,代码来源:repo.ts


示例4: getHTMLURL

 allAccounts.find(a => {
   const htmlURL = getHTMLURL(a.endpoint)
   const parsedEndpoint = URL.parse(htmlURL)
   return parsedURL.hostname === parsedEndpoint.hostname
 }) || null
开发者ID:ghmoore,项目名称:desktop,代码行数:5,代码来源:find-account.ts


示例5: decodeURI

    let server = http.createServer((req, res) => {
        let error = (code: number, msg: string = null) => {
            res.writeHead(code, { "Content-Type": "text/plain" })
            res.end(msg || "Error " + code)
        }

        let sendJson = (v: any) => {
            res.writeHead(200, { 'Content-Type': 'application/json; charset=utf8' })
            res.end(JSON.stringify(v))
        }

        let sendHtml = (s: string) => {
            res.writeHead(200, { 'Content-Type': 'text/html; charset=utf8' })
            res.end(s)
        }

        let sendFile = (filename: string) => {
            let stat = fs.statSync(filename);

            res.writeHead(200, {
                'Content-Type': U.getMime(filename),
                'Content-Length': stat.size
            });

            fs.createReadStream(filename).pipe(res);
        }

        let pathname = decodeURI(url.parse(req.url).pathname);

        if (pathname == "/") {
            res.writeHead(301, { location: '/index.html' })
            res.end()
            return
        }
        
        if (pathname.slice(0, appTarget.id.length + 2) == "/" + appTarget.id + "/") {
            res.writeHead(301, { location: req.url.slice(appTarget.id.length + 1) })
            res.end()
            return            
        }

        let elts = pathname.split("/").filter(s => !!s)
        if (elts.some(s => s[0] == ".")) {
            return error(400, "Bad path :-(\n")
        }

        if (elts[0] == "api") {
            return handleApiAsync(req, res, elts)
                .then(sendJson, err => {
                    if (err.statusCode) {
                        error(err.statusCode)
                        console.log("Error " + err.statusCode)
                    }
                    else {
                        error(500)
                        console.log(err.stack)
                    }
                })
        }

        if (pathname == "/--embed") {
            // use microbit for now
            res.writeHead(302, { location: 'https://codemicrobit.com/--embed' })
            res.end()
            return
        }

        if (!/\.js\.map$/.test(pathname)) {
            for (let dir of dirs) {
                let filename = path.resolve(path.join(dir, pathname))
                if (fileExistsSync(filename)) {
                    sendFile(filename)
                    return;
                }
            }
        }

        let webFile = path.join(docsDir, pathname)
        if (!fileExistsSync(webFile)) {
            if (fileExistsSync(webFile + ".html")) {
                webFile += ".html"
                pathname += ".html"
            } else if (fileExistsSync(webFile + ".md")) {
                webFile += ".md"
                pathname += ".md"
            }
        }

        if (fileExistsSync(webFile)) {
            if (/\.md$/.test(webFile)) {
                let html = ks.docs.renderMarkdown(docsTemplate, fs.readFileSync(webFile, "utf8"))
                sendHtml(html)
            } else {
                sendFile(webFile)
            }
            return
        }

        return error(404, "Not found :(\n")
    });
开发者ID:joben,项目名称:kindscript,代码行数:100,代码来源:server.ts


示例6: httpConnectionRequest

export async function httpConnectionRequest(
  address: string,
  authExp: Expression,
  context: {},
  allowBasicAuth: boolean,
  timeout: number
): Promise<void> {
  const now = Date.now();
  const options: http.RequestOptions = parse(address);
  if (options.protocol !== "http:")
    throw new Error("Invalid connection request URL or protocol");

  options.agent = new http.Agent({
    maxSockets: 1,
    keepAlive: true
  });

  let authHeader: {};
  let username: string;
  let password: string;

  while (!authHeader || (username != null && password != null)) {
    let opts = options;
    if (authHeader) {
      if (authHeader["method"] === "Basic") {
        if (!allowBasicAuth)
          throw new Error("Basic HTTP authentication not allowed");

        opts = Object.assign(
          {
            headers: {
              Authorization: auth.basic(username || "", password || "")
            }
          },
          options
        );
      } else if (authHeader["method"] === "Digest") {
        opts = Object.assign(
          {
            headers: {
              Authorization: auth.digest(
                username,
                password,
                options.path,
                "GET",
                null,
                authHeader
              )
            }
          },
          options
        );
      } else {
        throw new Error("Unrecognized auth method");
      }
    }

    let res = await httpGet(opts, timeout);

    // Workaround for some devices unexpectedly closing the connection
    if (res.statusCode === 0 && authHeader) res = await httpGet(opts, timeout);
    if (res.statusCode === 0) throw new Error("Device is offline");
    if (res.statusCode === 200 || res.statusCode === 204) return;

    if (res.statusCode === 401 && res.headers["www-authenticate"]) {
      authHeader = auth.parseAuthHeader(res.headers["www-authenticate"]);
      [username, password, authExp] = extractAuth(authExp, context, now, false);
    } else {
      throw new Error(
        `Unexpected response code from device: ${res.statusCode}`
      );
    }
  }
  throw new Error("Incorrect connection request credentials");
}
开发者ID:zaidka,项目名称:genieacs,代码行数:75,代码来源:connection-request.ts


示例7: decodeURI

    let server = http.createServer((req, res) => {
        let error = (code: number, msg: string = null) => {
            res.writeHead(code, { "Content-Type": "text/plain" })
            res.end(msg || "Error " + code)
        }

        let sendJson = (v: any) => {
            res.writeHead(200, { 'Content-Type': 'application/json; charset=utf8' })
            res.end(JSON.stringify(v))
        }

        let sendHtml = (s: string) => {
            res.writeHead(200, { 'Content-Type': 'text/html; charset=utf8' })
            res.end(s)
        }

        let sendFile = (filename: string) => {
            let stat = fs.statSync(filename);

            res.writeHead(200, {
                'Content-Type': U.getMime(filename),
                'Content-Length': stat.size
            });

            fs.createReadStream(filename).pipe(res);
        }

        let pathname = decodeURI(url.parse(req.url).pathname);

        if (pathname == "/") {
            res.writeHead(301, { location: '/index.html' })
            res.end()
            return
        }

        let elts = pathname.split("/").filter(s => !!s)
        if (elts.some(s => s[0] == ".")) {
            return error(400, "Bad path :-(\n")
        }

        if (elts[0] == "api") {
            if (!isAuthorizedLocalRequest(req)) {
                error(403);
                return null;
            }

            return handleApiAsync(req, res, elts)
                .then(sendJson, err => {
                    if (err.statusCode) {
                        error(err.statusCode)
                        console.log("Error " + err.statusCode)
                    }
                    else {
                        error(500)
                        console.log(err.stack)
                    }
                })
        }

        if (options.packaged) {
            let filename = path.resolve(path.join(packagedDir, pathname))
            if (fileExistsSync(filename)) {
                return sendFile(filename)
            } else {
                return error(404, "Packaged file not found")
            }
        }

        if (pathname.slice(0, pxt.appTarget.id.length + 2) == "/" + pxt.appTarget.id + "/") {
            res.writeHead(301, { location: req.url.slice(pxt.appTarget.id.length + 1) })
            res.end()
            return
        }

        if (pathname == "/--embed") {
            sendFile(path.join(fileDir, 'node_modules/pxt-core/webapp/public/embed.js'));
            return
        }

        if (pathname == "/--run") {
            sendFile(path.join(fileDir, 'node_modules/pxt-core/webapp/public/run.html'));
            return
        }

        if (pathname == "/--docs") {
            sendFile(path.join(fileDir, 'node_modules/pxt-core/webapp/public/docs.html'));
            return
        }

        if (!/\.js\.map$/.test(pathname)) {
            let dd = dirs
            if (U.startsWith(pathname, "/sim/")) {
                pathname = pathname.slice(4)
                dd = simdirs
            } else if (U.startsWith(pathname, "/cdn/")) {
                pathname = pathname.slice(4)
                dd = dirs
            } else if (U.startsWith(pathname, "/docfiles/")) {
                pathname = pathname.slice(10)
                dd = docfilesdirs
//.........这里部分代码省略.........
开发者ID:thomasdenney,项目名称:pxt,代码行数:101,代码来源:server.ts


示例8:

 snippet => {
   const newIssueUrl = url.parse('https://github.com/rust-lang/rust/issues/new', true);
   newIssueUrl.query = { body: snippet };
   return url.format(newIssueUrl);
 },
开发者ID:integer32llc,项目名称:rust-playground,代码行数:5,代码来源:index.ts


示例9: testCodeInjectEndRnNR

    "return"?: number;
}



/**
 * FakeApi - fetch parameter creator
 */
export const FakeApiFetchParamCreator = {
    /** 
     * To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
     * @param test code inject * &#39; &quot; &#x3D;end  rn n r To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
     */
    testCodeInjectEndRnNR(params: {  "test code inject * &#39; &quot; &#x3D;end  rn n r"?: string; }, options?: any): FetchArgs {
        const baseUrl = `/fake`;
        let urlObj = url.parse(baseUrl, true);
        let fetchOptions: RequestInit = assign({}, { method: "PUT" }, options);

        let contentTypeHeader: Dictionary<string> = {};
        contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" };
        fetchOptions.body = querystring.stringify({
            "test code inject */ &#39; &quot; &#x3D;end -- \r\n \n \r": params["test code inject * &#39; &quot; &#x3D;end  rn n r"],
        });
        if (contentTypeHeader) {
            fetchOptions.headers = contentTypeHeader;
        }
        return {
            url: url.format(urlObj),
            options: fetchOptions,
        };
    },
开发者ID:Cosium,项目名称:swagger-codegen,代码行数:31,代码来源:api.ts



注:本文中的url.parse函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript url.resolve函数代码示例发布时间:2022-05-25
下一篇:
TypeScript url.format函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap