url#parse JavaScript Examples

The following examples show how to use url#parse. 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: tokenlist.js    From habitat-rollup with The Unlicense 6 votes vote down vote up
export async function ipfsPush (files) {
  const boundary = 'x';
  const headers = {
    'content-type': 'multipart/form-data; boundary=' + boundary,
  };
  const coder = new TextEncoder();
  let data = [];

  for (const f in files) {
    const payload = files[f];
    const filename = encodeURIComponent(f);
    const str = `--${boundary}\r\ncontent-disposition: form-data; name="file"; filename="${filename}"\r\ncontent-type: application/octet-stream\r\n\r\n`;
    const head = Array.from(coder.encode(str));
    const tail = Array.from(coder.encode('\r\n'));

    data = data.concat(head).concat(Array.from(payload)).concat(tail);
  }

  data = data.concat(Array.from(coder.encode('--' + boundary + '--\r\n')));

  const ret = await fetch(IPFS_ADD, headers, data);
  return ret.toString().split('\n').slice(0, -1).map((str) => JSON.parse(str));
}
Example #2
Source File: tokenlist.js    From habitat-rollup with The Unlicense 6 votes vote down vote up
async function fetch (url, headers = {}, payload) {
  const fetchOptions = parse(url);
  const proto = https;

  fetchOptions.headers = headers;
  fetchOptions.method = payload ? 'POST' : 'GET';

  return new Promise(
    function (resolve, reject) {
      const req = proto.request(fetchOptions);
      let body = Buffer.alloc(0);

      req.on('error', reject);
      req.on('response', function (resp) {
        resp.on('data', function (buf) {
          body = Buffer.concat([body, buf]);
        });
        resp.on('end', function () {
          console.log(url, resp.statusCode);
          if (resp.statusCode !== 200) {
            return reject(body);
          }

          resolve(body);
        });
      });

      req.end(payload ? Buffer.from(payload) : null);
    }
  );
}
Example #3
Source File: urls.js    From cli with MIT License 6 votes vote down vote up
export function parseHyperUrl (str, parseQS) {
  // prepend the scheme if it's missing
  if (!SCHEME_REGEX.test(str)) {
    str = 'hyper://' + str
  }

  var parsed, version = null, match = VERSION_REGEX.exec(str)
  if (match) {
    // run typical parse with version segment removed
    parsed = parse((match[1] || '') + (match[2] || '') + (match[4] || ''), parseQS)
    version = match[3].slice(1)
  } else {
    parsed = parse(str, parseQS)
  }
  parsed.href = str // overwrite href to include actual original
  if (!parsed.query && parsed.searchParams) {
    parsed.query = Object.fromEntries(parsed.searchParams) // to match node
  }
  parsed.version = version // add version segment
  if (!parsed.origin) parsed.origin = `hyper://${parsed.hostname}/`
  return parsed
}
Example #4
Source File: home.js    From smart-node-tpl with MIT License 6 votes vote down vote up
Home = (req, res) => {
  let curPath = parse(req.url).pathname
  if(curPath === '/home'){
    res.setHeader('Content-Type','text/html;charset=utf-8')
    let data = getData()
    res.end(
      `
       <h1>我是${curPath}页面</h1>
       <p>${data.name}</p>
       <p>${data.author}</p>
       <p>${data.cate}</p>
      `
    )
  }
}
Example #5
Source File: _mock.js    From prometheusPro with MIT License 5 votes vote down vote up
function getRule(req, res, u) {
  let url = u;

  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    // eslint-disable-next-line prefer-destructuring
    url = req.url;
  }

  const params = parse(url, true).query;
  let dataSource = tableListDataSource;

  if (params.sorter) {
    const s = params.sorter.split('_');
    dataSource = dataSource.sort((prev, next) => {
      if (s[1] === 'descend') {
        return next[s[0]] - prev[s[0]];
      }

      return prev[s[0]] - next[s[0]];
    });
  }

  if (params.status) {
    const status = params.status.split(',');
    let filterDataSource = [];
    status.forEach(s => {
      filterDataSource = filterDataSource.concat(
        dataSource.filter(item => {
          if (parseInt(`${item.status}`, 10) === parseInt(s.split('')[0], 10)) {
            return true;
          }

          return false;
        }),
      );
    });
    dataSource = filterDataSource;
  }

  if (params.name) {
    dataSource = dataSource.filter(data => data.name.includes(params.name || ''));
  }

  let pageSize = 10;

  if (params.pageSize) {
    pageSize = parseInt(`${params.pageSize}`, 0);
  }

  const result = {
    data: dataSource,
    total: dataSource.length,
    success: true,
    pageSize,
    current: parseInt(`${params.currentPage}`, 10) || 1,
  };
  return res.json(result);
}
Example #6
Source File: index.es.js    From Lynx with MIT License 5 votes vote down vote up
constructor(input) {
		let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

		let parsedURL;

		// normalize input
		if (!isRequest(input)) {
			if (input && input.href) {
				// in order to support Node.js' Url objects; though WHATWG's URL objects
				// will fall into this branch also (since their `toString()` will return
				// `href` property anyway)
				parsedURL = parse(input.href);
			} else {
				// coerce input to a string before attempting to parse
				parsedURL = parse(`${input}`);
			}
			input = {};
		} else {
			parsedURL = parse(input.url);
		}

		let method = init.method || input.method || 'GET';
		method = method.toUpperCase();

		if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
			throw new TypeError('Request with GET/HEAD method cannot have body');
		}

		let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;

		Body.call(this, inputBody, {
			timeout: init.timeout || input.timeout || 0,
			size: init.size || input.size || 0
		});

		const headers = new Headers(init.headers || input.headers || {});

		if (init.body != null) {
			const contentType = extractContentType(this);
			if (contentType !== null && !headers.has('Content-Type')) {
				headers.append('Content-Type', contentType);
			}
		}

		this[INTERNALS$2] = {
			method,
			redirect: init.redirect || input.redirect || 'follow',
			headers,
			parsedURL
		};

		// node-fetch-only options
		this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
		this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
		this.counter = init.counter || input.counter || 0;
		this.agent = init.agent || input.agent;
	}
Example #7
Source File: rule.js    From youdidao-unmanned-shop with MIT License 5 votes vote down vote up
function getRule(req, res, u) {
  let url = u;
  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    url = req.url; // eslint-disable-line
  }

  const params = parse(url, true).query;

  let dataSource = tableListDataSource;

  if (params.sorter) {
    const s = params.sorter.split('_');
    dataSource = dataSource.sort((prev, next) => {
      if (s[1] === 'descend') {
        return next[s[0]] - prev[s[0]];
      }
      return prev[s[0]] - next[s[0]];
    });
  }

  if (params.status) {
    const status = params.status.split(',');
    let filterDataSource = [];
    status.forEach(s => {
      filterDataSource = filterDataSource.concat(
        dataSource.filter(data => parseInt(data.status, 10) === parseInt(s[0], 10))
      );
    });
    dataSource = filterDataSource;
  }

  if (params.name) {
    dataSource = dataSource.filter(data => data.name.indexOf(params.name) > -1);
  }

  let pageSize = 10;
  if (params.pageSize) {
    pageSize = params.pageSize * 1;
  }

  const result = {
    list: dataSource,
    pagination: {
      total: dataSource.length,
      pageSize,
      current: parseInt(params.currentPage, 10) || 1,
    },
  };

  return res.json(result);
}
Example #8
Source File: google-auth.js    From Quest with MIT License 5 votes vote down vote up
function signInWithPopup(clientId, { scope }) {
  return new Promise((resolve, reject) => {
    const authWindow = new remote.BrowserWindow({
      width: 500,
      height: 600,
      show: true,
    });

    const authUrl = `${GOOGLE_AUTHORIZATION_URL}?${qs.stringify({
      response_type: "code",
      redirect_uri: getRedirectUri(clientId),
      client_id: clientId,
      scope,
    })}`;

    function handleNavigation(url) {
      const { query } = parse(url, true);
      if (!query) {
        return;
      }

      if (query.error) {
        reject(new Error(`There was an error: ${query.error}`));
      } else if (query.code) {
        // Login is complete
        authWindow.removeAllListeners("closed");
        setImmediate(() => authWindow.close());

        // This is the authorization code we need to request tokens
        resolve(query.code);
      }
    }

    authWindow.on("closed", () => {
      throw new Error("Auth window was closed by user");
    });

    authWindow.webContents.on("will-navigate", (event, url) => {
      handleNavigation(url);
    });

    authWindow.webContents.on("did-get-redirect-request", (event, oldUrl, newUrl) =>
      handleNavigation(newUrl)
    );

    authWindow.loadURL(authUrl);
  });
}
Example #9
Source File: settings.js    From Quest with MIT License 5 votes vote down vote up
function signInWithPopup(configuration) {
  const http = require("http");

  const {
    clientId,
    clientSecret,
    redirectPort = getDefaultForProperty("slack", "redirectPort"),
  } = configuration.get();

  const authWindow = new remote.BrowserWindow({ width: 600, height: 800, show: true });
  const redirectUri = `http://localhost:${redirectPort}`;

  let httpServer;
  try {
    httpServer = http.createServer(async (req, res) => {
      res.writeHead(200, { "Content-Type": "html" });
      const { query } = parse(req.url);
      res.end("loading...");

      const code = qs.parse(query).code;
      if (!code) {
        authWindow.close();
        return;
      }

      try {
        const r = await fetch(
          "https://slack.com/api/oauth.access?" +
            qs.stringify({
              code,
              client_id: clientId,
              redirect_uri: redirectUri,
              client_secret: clientSecret,
            })
        );

        const body = await r.json();
        configuration.nested.token.set(body.access_token);
        configuration.nested.userId.set(body.user_id);
        notify("Authentication to Slack successful");
      } catch (e) {
        notify("Failure when authenticating to Slack");
        log.error(e);
      } finally {
        authWindow.close();
      }
    });

    httpServer.listen(redirectPort, "127.0.0.1");

    const authUrl = `https://slack.com/oauth/authorize?${qs.stringify({
      client_id: clientId,
      redirect_uri: redirectUri,
      scope: "users:read search:read emoji:read",
    })}`;

    authWindow.on("closed", () => {
      try {
        httpServer.close();
      } catch (e) {
        log.warn("unable to close http server", e);
      }
    });

    authWindow.loadURL(authUrl);
  } catch (e) {
    if (httpServer) {
      httpServer.close();
    }
  }
}
Example #10
Source File: index.es.js    From ipfs-action with MIT License 5 votes vote down vote up
Body.prototype = {
  get bodyUsed() {
    return this[DISTURBED];
  },

  /**
   * Decode response as ArrayBuffer
   *
   * @return {Promise}
   */
  arrayBuffer() {
    return consumeBody.call(this).then(buf => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
  },

  /**
   * Return raw response as Blob
   *
   * @return {Promise}
   */
  blob() {
    const ct = this.headers && this.headers.get('content-type') || '';
    return consumeBody.call(this).then(buf => Object.assign( // Prevent copying
    new Blob([], {
      type: ct.toLowerCase()
    }), {
      [BUFFER]: buf
    }));
  },

  /**
   * Decode response as json
   *
   * @return {Promise}
   */
  json() {
    return consumeBody.call(this).then(buffer => JSON.parse(buffer.toString()));
  },

  /**
   * Decode response as text
   *
   * @return {Promise}
   */
  text() {
    return consumeBody.call(this).then(buffer => buffer.toString());
  },

  /**
   * Decode response as buffer (non-spec api)
   *
   * @return {Promise}
   */
  buffer() {
    return consumeBody.call(this);
  },

  /**
   * Decode response as text, while automatically detecting the encoding and
   * trying to decode to UTF-8 (non-spec api)
   *
   * @return {Promise}
   */
  textConverted() {
    return consumeBody.call(this).then(buffer => convertBody(buffer, this.headers));
  }

};
Example #11
Source File: index.es.js    From ipfs-action with MIT License 5 votes vote down vote up
constructor(input, init = {}) {
    let parsedURL; // normalize input

    if (!(input instanceof Request)) {
      if (input && input.href) {
        // in order to support Node.js' Url objects; though WHATWG's URL objects
        // will fall into this branch also (since their `toString()` will return
        // `href` property anyway)
        parsedURL = parse(input.href);
      } else {
        // coerce input to a string before attempting to parse
        parsedURL = parse(`${input}`);
      }

      input = {};
    } else {
      parsedURL = parse(input.url);
    }

    const method = init.method || input.method || 'GET';

    if ((init.body != null || input instanceof Request && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
      throw new TypeError('Request with GET/HEAD method cannot have body');
    }

    const inputBody = init.body != null ? init.body : input instanceof Request && input.body !== null ? clone(input) : null;
    Body.call(this, inputBody, {
      timeout: init.timeout || input.timeout || 0,
      size: init.size || input.size || 0
    }); // fetch spec options

    this.method = method.toUpperCase();
    this.redirect = init.redirect || input.redirect || 'follow';
    this.signal = init.signal || input.signal || null;
    this.headers = new Headers(init.headers || input.headers || {});
    this.headers.delete('Content-Length'); // user cannot set content-length themself as per fetch spec

    this.chunkedEncoding = false;
    this.useElectronNet = init.useElectronNet !== undefined // have to do this instead of || because it can be set to false
    ? init.useElectronNet : input.useElectronNet; // istanbul ignore if

    if (this.useElectronNet && !process.versions.electron) throw new Error('Cannot use Electron/net module on Node.js!');

    if (this.useElectronNet === undefined) {
      this.useElectronNet = Boolean(process.versions.electron);
    }

    if (this.useElectronNet) {
      this.useSessionCookies = init.useSessionCookies !== undefined ? init.useSessionCookies : input.useSessionCookies;
    }

    if (init.body != null) {
      const contentType = extractContentType(this);

      if (contentType !== null && !this.headers.has('Content-Type')) {
        this.headers.append('Content-Type', contentType);
      }
    } // server only options


    this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
    this.counter = init.counter || input.counter || 0;
    this.session = init.session || input.session;
    this[PARSED_URL] = parsedURL;
    Object.defineProperty(this, Symbol.toStringTag, {
      value: 'Request',
      writable: false,
      enumerable: false,
      configurable: true
    });
  }
Example #12
Source File: rule.js    From online-test-platform with Apache License 2.0 5 votes vote down vote up
function getRule(req, res, u) {
  let url = u;
  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    url = req.url; // eslint-disable-line
  }

  const params = parse(url, true).query;

  let dataSource = tableListDataSource;

  if (params.sorter) {
    const s = params.sorter.split('_');
    dataSource = dataSource.sort((prev, next) => {
      if (s[1] === 'descend') {
        return next[s[0]] - prev[s[0]];
      }
      return prev[s[0]] - next[s[0]];
    });
  }

  if (params.status) {
    const status = params.status.split(',');
    let filterDataSource = [];
    status.forEach(s => {
      filterDataSource = filterDataSource.concat(
        dataSource.filter(data => parseInt(data.status, 10) === parseInt(s[0], 10))
      );
    });
    dataSource = filterDataSource;
  }

  if (params.name) {
    dataSource = dataSource.filter(data => data.name.indexOf(params.name) > -1);
  }

  let pageSize = 10;
  if (params.pageSize) {
    pageSize = params.pageSize * 1;
  }

  const result = {
    list: dataSource,
    pagination: {
      total: dataSource.length,
      pageSize,
      current: parseInt(params.currentPage, 10) || 1,
    },
  };

  return res.json(result);
}
Example #13
Source File: admin.js    From smart-node-tpl with MIT License 5 votes vote down vote up
Admin = (req, res) => {
  let curPath = parse(req.url).pathname
  if(curPath === '/admin'){
    res.setHeader('Content-Type','text/plain;charset=utf-8')
    res.end(`我是${curPath}页面`)
  }
}
Example #14
Source File: _mock.js    From vpp with MIT License 5 votes vote down vote up
function getRule(req, res, u) {
  let realUrl = u;

  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }

  const { current = 1, pageSize = 10 } = req.query;
  const params = parse(realUrl, true).query;
  let dataSource = [...tableListDataSource].slice((current - 1) * pageSize, current * pageSize);
  const sorter = JSON.parse(params.sorter);

  if (sorter) {
    dataSource = dataSource.sort((prev, next) => {
      let sortNumber = 0;
      Object.keys(sorter).forEach(key => {
        if (sorter[key] === 'descend') {
          if (prev[key] - next[key] > 0) {
            sortNumber += -1;
          } else {
            sortNumber += 1;
          }

          return;
        }

        if (prev[key] - next[key] > 0) {
          sortNumber += 1;
        } else {
          sortNumber += -1;
        }
      });
      return sortNumber;
    });
  }

  if (params.filter) {
    const filter = JSON.parse(params.filter);

    if (Object.keys(filter).length > 0) {
      dataSource = dataSource.filter(item =>
        Object.keys(filter).some(key => {
          if (!filter[key]) {
            return true;
          }

          if (filter[key].includes(`${item[key]}`)) {
            return true;
          }

          return false;
        }),
      );
    }
  }

  if (params.name) {
    dataSource = dataSource.filter(data => data.name.includes(params.name || ''));
  }

  const result = {
    data: dataSource,
    total: tableListDataSource.length,
    success: true,
    pageSize,
    current: parseInt(`${params.currentPage}`, 10) || 1,
  };
  return res.json(result);
}
Example #15
Source File: listTableList.js    From vpp with MIT License 5 votes vote down vote up
function getRule(req, res, u) {
  let realUrl = u;

  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }

  const { current = 1, pageSize = 10 } = req.query;
  const params = parse(realUrl, true).query;
  let dataSource = [...tableListDataSource].slice((current - 1) * pageSize, current * pageSize);
  const sorter = JSON.parse(params.sorter);

  if (sorter) {
    dataSource = dataSource.sort((prev, next) => {
      let sortNumber = 0;
      Object.keys(sorter).forEach(key => {
        if (sorter[key] === 'descend') {
          if (prev[key] - next[key] > 0) {
            sortNumber += -1;
          } else {
            sortNumber += 1;
          }

          return;
        }

        if (prev[key] - next[key] > 0) {
          sortNumber += 1;
        } else {
          sortNumber += -1;
        }
      });
      return sortNumber;
    });
  }

  if (params.filter) {
    const filter = JSON.parse(params.filter);

    if (Object.keys(filter).length > 0) {
      dataSource = dataSource.filter(item =>
        Object.keys(filter).some(key => {
          if (!filter[key]) {
            return true;
          }

          if (filter[key].includes(`${item[key]}`)) {
            return true;
          }

          return false;
        }),
      );
    }
  }

  if (params.name) {
    dataSource = dataSource.filter(data => data.name.includes(params.name || ''));
  }

  const result = {
    data: dataSource,
    total: tableListDataSource.length,
    success: true,
    pageSize,
    current: parseInt(`${params.currentPage}`, 10) || 1,
  };
  return res.json(result);
}
Example #16
Source File: rule.js    From acy-dex-interface with MIT License 5 votes vote down vote up
function getRule(req, res, u) {
  let url = u;
  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    url = req.url; // eslint-disable-line
  }

  const params = parse(url, true).query;

  let dataSource = tableListDataSource;

  if (params.sorter) {
    const s = params.sorter.split('_');
    dataSource = dataSource.sort((prev, next) => {
      if (s[1] === 'descend') {
        return next[s[0]] - prev[s[0]];
      }
      return prev[s[0]] - next[s[0]];
    });
  }

  if (params.status) {
    const status = params.status.split(',');
    let filterDataSource = [];
    status.forEach(s => {
      filterDataSource = filterDataSource.concat(
        dataSource.filter(data => parseInt(data.status, 10) === parseInt(s[0], 10))
      );
    });
    dataSource = filterDataSource;
  }

  if (params.name) {
    dataSource = dataSource.filter(data => data.name.indexOf(params.name) > -1);
  }

  let pageSize = 10;
  if (params.pageSize) {
    pageSize = params.pageSize * 1;
  }

  const result = {
    list: dataSource,
    pagination: {
      total: dataSource.length,
      pageSize,
      current: parseInt(params.currentPage, 10) || 1,
    },
  };

  return res.json(result);
}
Example #17
Source File: tokenlist.js    From habitat-rollup with The Unlicense 5 votes vote down vote up
compareList = JSON.parse(fs.readFileSync(OUTPUT_PATH)).tokens
Example #18
Source File: tokenlist.js    From habitat-rollup with The Unlicense 5 votes vote down vote up
data = JSON.parse(await fetch('https://zapper.fi/api/token-list'))
Example #19
Source File: index.es.js    From Lynx with MIT License 4 votes vote down vote up
Body.prototype = {
	get body() {
		return this[INTERNALS].body;
	},

	get bodyUsed() {
		return this[INTERNALS].disturbed;
	},

	/**
  * Decode response as ArrayBuffer
  *
  * @return  Promise
  */
	arrayBuffer() {
		return consumeBody.call(this).then(function (buf) {
			return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
		});
	},

	/**
  * Return raw response as Blob
  *
  * @return Promise
  */
	blob() {
		let ct = this.headers && this.headers.get('content-type') || '';
		return consumeBody.call(this).then(function (buf) {
			return Object.assign(
			// Prevent copying
			new Blob([], {
				type: ct.toLowerCase()
			}), {
				[BUFFER]: buf
			});
		});
	},

	/**
  * Decode response as json
  *
  * @return  Promise
  */
	json() {
		var _this2 = this;

		return consumeBody.call(this).then(function (buffer) {
			try {
				return JSON.parse(buffer.toString());
			} catch (err) {
				return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
			}
		});
	},

	/**
  * Decode response as text
  *
  * @return  Promise
  */
	text() {
		return consumeBody.call(this).then(function (buffer) {
			return buffer.toString();
		});
	},

	/**
  * Decode response as buffer (non-spec api)
  *
  * @return  Promise
  */
	buffer() {
		return consumeBody.call(this);
	},

	/**
  * Decode response as text, while automatically detecting the encoding and
  * trying to decode to UTF-8 (non-spec api)
  *
  * @return  Promise
  */
	textConverted() {
		var _this3 = this;

		return consumeBody.call(this).then(function (buffer) {
			return convertBody(buffer, _this3.headers);
		});
	}

};