JavaScriptでURLを作ったり加工したりする
Node.js v7から標準のurlモジュールにいい感じのparserが付いて便利になったshokai.icon window.locationと同じフォーマットで扱えるparserだが
parseしたURLを加工したりするのにも使える
URLを作る
code:js
var url = require('url')
undefined
var u = new url.Url()
undefined
u.format()
''
u.pathname = '/p/a/t/h'
'/p/a/t/h'
u.format()
'/p/a/t/h'
u.protocol = 'https'
'https'
u.format()
'https:/p/a/t/h'
u.host = 'shokai.org'
'shokai.org'
u.format()
u.query = { aaa: 1234, bbb: 'BBBB'}
{ aaa: 1234, bbb: 'BBBB' }
u.format()
u.port = 3000
3000
u.format()
portが対応してないようだ
URLを加工する
url.parse(string)で出てくるobjectはurl.Urlのインスタンス
code:js
true
url.parse(string)後のobjectの各プロパティを変更してから、format()すると文字列に戻せる
code:js
undefined
u.format()
u
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'shokai.org',
port: null,
hostname: 'shokai.org',
hash: null,
search: '?aaa=123&bbb=BBB',
query: 'aaa=123&bbb=BBB',
pathname: '/p/a/t/h',
path: '/p/a/t/h?aaa=123&bbb=BBB',
undefined
u.format()
u.query += '&cccc=9876'
'aaa=123&bbb=BBB&cccc=9876'
u.auth = null
null
u.format()
u.pathname = '/api' + u.pathname
'/api/p/a/t/h'
u.format()