[英]Node's console is not showing all the object properties ... is this expected behavior?
我做了一個
console.log(myURL);
並且沒有看到擴展屬性
console.log(myURL.extension);
但是如果我自己登錄它,它會正確顯示該值。
found 是一個這樣創建的 URL 對象:
const url = require('url');
let myURL = new URL(test);
添加了缺失的屬性:
myURL.extension = test.split('.').pop();
輸出如下所示:
URL {
href: 'https://www.imdb.com/favicon.ico',
origin: 'https://www.imdb.com',
protocol: 'https:',
username: '',
password: '',
host: 'www.imdb.com',
hostname: 'www.imdb.com',
port: '',
pathname: '/favicon.ico',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
示例代碼:
const url = require('url');
const test = 'https://www.imdb.com/favicon.ico';
let myURL = new URL(test);
myURL.extension = test.split('.').pop();
console.log(myURL);
這種行為的原因是因為URL
的prototype
定義了一個util.inspect.custom
覆蓋。 例如在 Node.js v12.11.0 中,它是這樣定義的:
> console.log(myURL[util.inspect.custom])
[inspect.custom](depth, opts) {
if (this == null ||
Object.getPrototypeOf(this[context]) !== URLContext.prototype) {
throw new ERR_INVALID_THIS('URL');
}
if (typeof depth === 'number' && depth < 0)
return this;
const ctor = getConstructorOf(this);
const obj = Object.create({
constructor: ctor === null ? URL : ctor
});
obj.href = this.href;
obj.origin = this.origin;
obj.protocol = this.protocol;
obj.username = this.username;
obj.password = this.password;
obj.host = this.host;
obj.hostname = this.hostname;
obj.port = this.port;
obj.pathname = this.pathname;
obj.search = this.search;
obj.searchParams = this.searchParams;
obj.hash = this.hash;
if (opts.showHidden) {
obj.cannotBeBase = this[cannotBeBase];
obj.special = this[special];
obj[context] = this[context];
}
return inspect(obj, opts);
}
如果您真的關心輸出格式,您可以覆蓋此行為並將extension
屬性作為 getter 添加到URL
類的prototype
:
const { URL } = require('url');
const { inspect } = require('util');
Object.defineProperty(URL.prototype, 'extension', {
enumerable: true,
configurable: true,
get() { return this.pathname.split('.').pop(); }
});
URL.prototype[inspect.custom] = function(depth, opts) {
if (typeof depth === 'number' && depth < 0) return this;
const keys = Object.keys(URL.prototype).filter(key => typeof this[key] !== 'function');
const obj = Object.create({ constructor: URL });
Object.assign(obj, ...keys.map(key => ({ [key]: this[key] })));
return inspect(obj, opts);
};
然后您的輸出格式將如下所示:
> new URL('https://www.imdb.com/favicon.ico')
URL {
href: 'https://www.imdb.com/favicon.ico',
origin: 'https://www.imdb.com',
protocol: 'https:',
username: '',
password: '',
host: 'www.imdb.com',
hostname: 'www.imdb.com',
port: '',
pathname: '/favicon.ico',
search: '',
searchParams: URLSearchParams {},
hash: '',
extension: 'ico'
}
但是,如果您不太在意,那么您可以接受您看到的輸出格式是預期的行為,並且您可以像通常在任何其他對象上一樣訪問extension
屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.