How to use the format function from url

Find comprehensive JavaScript url.format code examples handpicked from public code repositorys.

url.format is a Node.js function that takes a URL object and returns a formatted URL string.

108
109
110
111
112
113
114
115
116
117
    })
    .catch(e => log.debug(e)); // Ignore errors, since this is non-essential
});

mainWindow.loadURL(
  url.format({
    pathname: path.join(__dirname, "../public/index.html"),
    protocol: "file",
    slashes: true
  })
fork icon118
star icon475
watch icon0

+ 5 other calls in file

1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
function convertUrlAndSetContext(urlPath, req, method) {
  const url = parseUrl(urlPath, req);
  const definition = lookupContextFromUrl(url, req);
  enrichRequest(definition, url, urlPath, req, method);
  convertUrl(url, req);
  return URL.format(url);
}

function parseUrl(urlPath, req) {
  const url = URL.parse(urlPath, true);
fork icon0
star icon3
watch icon3

+ 3 other calls in file

How does url.format work?

url.format is a function in the Node.js url module that takes a URL object and returns a formatted URL string. When you call url.format with a URL object as its argument, it constructs a URL string based on the properties of the object. The URL string contains the protocol, hostname, port, path, query parameters, and fragment identifier specified in the object. If the URL object contains a hostname property but no protocol property, url.format will assume that the protocol is http by default. If the object contains a path property but no hostname property, url.format will assume that the hostname is localhost by default. url.format can be used to create a formatted URL string from a URL object that was created using url.parse, or to construct a URL string directly from a plain object that has the same properties as a URL object. url.format can also be used to modify certain parts of an existing URL string by passing a URL object that contains only the parts you want to change. By using url.format to construct and manipulate URL strings in a consistent and reliable manner, you can avoid errors and inconsistencies that can arise from manually constructing or modifying URL strings.

206
207
208
209
210
211
212
213
214
215
  }
  const pathObj = url.parse(options.path || '/')
  urlObj.pathname = pathObj.pathname
  urlObj.search = pathObj.search
  urlObj.hash = pathObj.hash
  urlStr = url.format(urlObj)
}

const redirectPolicy = options.redirect || 'follow'
if (!['follow', 'error', 'manual'].includes(redirectPolicy)) {
fork icon0
star icon2
watch icon0

257
258
259
260
261
262
263
264
265
266
if (!self.uri.pathname) { self.uri.pathname = '/' }

if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
  // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
  // Detect and reject it as soon as possible
  var faultyUri = url.format(self.uri)
  var message = 'Invalid URI "' + faultyUri + '"'
  if (Object.keys(options).length === 0) {
    // No option ? This can be the sign of a redirect
    // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
fork icon0
star icon0
watch icon1

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const url = require("url");

// Define a URL object
const urlObj = {
  protocol: "https",
  hostname: "www.example.com",
  pathname: "/path/to/resource",
  search: "?param1=value1&param2=value2",
  hash: "section1",
};

// Format the URL object into a string using url.format
const urlString = url.format(urlObj);

// Output the formatted URL string to the console
console.log(urlString);

In this example, we start by defining a URL object that contains a protocol, hostname, path, query parameters, and a fragment identifier. We then pass that object to url.format to construct a formatted URL string based on its properties. Prettier then returns a new string containing the formatted URL. We output that string to the console using console.log. The output of this example will be a formatted URL string: ruby Copy code

287
288
289
290
291
292
293
294
295
}

// RFC7230§5.3.1: When making a request directly to an origin server, […]
// a client MUST send only the absolute path […] as the request-target.
this._currentUrl = /^\//.test(this._options.path) ?
  url.format(this._options) :
  // When making a request to a proxy, […]
  // a client MUST send the target URI in absolute-form […].
  this._options.path;
fork icon0
star icon0
watch icon1

+ 7 other calls in file

6
7
8
9
10
11
12
13
14
15
  path = (event.pathParameters && event.pathParameters.proxy && `/${event.pathParameters.proxy}`) || event.path,
  // NOTE: Strip base path for custom domains
  stripBasePath = '',
  replaceRegex = new RegExp(`^${stripBasePath}`)
}) {
  return url.format({
    pathname: path.replace(replaceRegex, ''),
    query
  })
}
fork icon0
star icon0
watch icon1

125
126
127
128
129
130
131
132
133
134
}
let query = typeof req.qs === 'string' ? req.qs : querystringify(req.qs, req.useQuerystring);
if (query) {
  pathObj.search = query;
}
path = url.format(pathObj);

if (path.indexOf("http:///") === 0) {
  path = path.replace("http:///", "/");
}
fork icon0
star icon0
watch icon1

23
24
25
26
27
28
29
30
31
32
33
34
// //////////////////////////////////////////////////////////////////////////////


const assert = require('assert');
const url = require('url');
const parseUrl = url.parse;
const formatUrl = url.format;
const parseQuery = require('querystring').parse;
const request = require('@arangodb/request');


function parse (str) {
fork icon0
star icon0
watch icon1

34
35
36
37
38
39
40
41
42
43

// and load the index.html of the app.
let indexPath

if (dev && process.argv.indexOf('--noDevServer') === -1) {
  indexPath = url.format({
    protocol: 'http:',
    host: 'localhost:8080',
    pathname: 'index.html',
    slashes: true
fork icon0
star icon0
watch icon0

1
2
3
4
5
6
7
8
9
10
11
const axios = require('axios');
const url = require('url');
const app = require('../src/app');


const port = app.get('port') || 8998;
const getUrl = pathname => url.format({
  hostname: app.get('host') || 'localhost',
  protocol: 'http',
  port,
  pathname
fork icon0
star icon0
watch icon0

27
28
29
30
31
32
33
34
35
36
});

mainWindow.loadURL(
  isDev
    ? 'http://localhost:3000'
    : url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true
      })
fork icon0
star icon0
watch icon0

102
103
104
105
106
107
108
109
110
111
    // e.g. /tag/bacon/page/2/  -> 'page/2' (to append)
    // e.g. /bacon/welcome/     -> '' (nothing to append)
    const matchPath = this.permalinks.getValue().replace(/:\w+/g, '[a-zA-Z0-9-_]+');
    const toAppend = req.url.replace(new RegExp(matchPath), '');

    return urlUtils.redirect301(res, url.format({
        pathname: urlUtils.createUrl(urlUtils.urlJoin(targetRoute, toAppend), false, false, true),
        search: url.parse(req.originalUrl).search
    }));
}
fork icon0
star icon0
watch icon0

127
128
129
130
131
132
133
134
135
The `hash` property consists of the "fragment" portion of the URL including
the leading ASCII hash (`#`) character.

For example: `'#hash'`

## url.format(urlObject)
<!-- YAML
added: v0.1.25
-->
fork icon0
star icon0
watch icon2

+ 11 other calls in file

170
171
172
173
174
175
176
177
178
179
it('supports windows opened from a <webview>', async () => {
  const webview = new WebView();
  const consoleMessage = waitForEvent(webview, 'console-message');
  webview.allowpopups = true;
  webview.setAttribute('webpreferences', 'contextIsolation=no');
  webview.src = url.format({
    pathname: `${fixtures}/pages/webview-opener-postMessage.html`,
    protocol: 'file',
    query: {
      p: `${fixtures}/pages/window-opener-postMessage.html`
fork icon0
star icon0
watch icon0

+ 11 other calls in file

195
196
197
198
199
200
201
202
203
204
  * The value of `urlObject.hash` is appended to `result`.
* Otherwise, if the `urlObject.hash` property is not `undefined` and is not a
  string, an [`Error`][] is thrown.
* `result` is returned.

## url.format(URL[, options])

> Stability: 1 - Experimental

* `URL` {URL} A [WHATWG URL][] object
fork icon0
star icon0
watch icon1

+ 7 other calls in file

31
32
33
34
35
36
37
38
39
40
  const event = await waitForEvent(webview, 'console-message');
  return event.message;
};

async function loadFileInWebView (webview, attributes = {}) {
  const thisFile = url.format({
    pathname: __filename.replace(/\\/g, '/'),
    protocol: 'file',
    slashes: true
  });
fork icon0
star icon0
watch icon3

+ 3 other calls in file