util module
Il modulo node:util supporta le esigenze delle API interne di Node.js. Molte delle utilità sono utili anche per gli sviluppatori di applicazioni e moduli. Per accedervi:
import util from 'node:util';
Vedere di origine
Classi
| MIMEParams |
L'API |
| MIMEType |
Implementazione di classe MIMEType. In conformità alle convenzioni del browser, tutte le proprietà degli oggetti Una stringa MIME è una stringa strutturata contenente più componenti significativi. Durante l'analisi, viene restituito un oggetto |
| TextDecoder |
Implementazione dell'API
|
| TextEncoder |
Implementazione dell'API
La classe |
Interfacce
Alias tipo
| CustomInspectFunction | |
| CustomPromisify | |
| DebugLoggerFunction | |
| DiffEntry | |
| ParseArgsOptionsType |
Tipo di argomento usato in parseArgs. |
| Style | |
Funzioni
| aborted(Abort |
È in ascolto dell'evento di interruzione nel
|
| add |
Aggiunge un parametro all'URL specificato |
| assign(any[]) | Copia i valori di tutte le proprietà enumerabili da uno o più oggetti di origine a un oggetto di destinazione e restituisce l'oggetto di destinazione. |
| auto |
Controlla se l'URL di incorporamento contiene autoAuth=true. |
| callbackify(() => Promise<void>) | Accetta una funzione
Stampa:
Il callback viene eseguito in modo asincrono e avrà un'analisi dello stack limitata.
Se il callback viene generato, il processo genererà un evento Poiché
|
| callbackify<T1, T2, T3, T4, T5, T6, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult>) | |
| callbackify<T1, T2, T3, T4, T5, T6>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>) | |
| callbackify<T1, T2, T3, T4, T5, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>) | |
| callbackify<T1, T2, T3, T4, T5>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>) | |
| callbackify<T1, T2, T3, T4, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>) | |
| callbackify<T1, T2, T3, T4>((arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>) | |
| callbackify<T1, T2, T3, TResult>((arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>) | |
| callbackify<T1, T2, T3>((arg1: T1, arg2: T2, arg3: T3) => Promise<void>) | |
| callbackify<T1, T2, TResult>((arg1: T1, arg2: T2) => Promise<TResult>) | |
| callbackify<T1, T2>((arg1: T1, arg2: T2) => Promise<void>) | |
| callbackify<T1, TResult>((arg1: T1) => Promise<TResult>) | |
| callbackify<T1>((arg1: T1) => Promise<void>) | |
| callbackify<TResult>(() => Promise<TResult>) | |
| create |
Genera una stringa di caratteri da 5 a 6 casuali. |
| debuglog(string, (fn: Debug |
Il
Se questo programma viene eseguito con
dove Il
se viene eseguito con
Nella variabile di ambiente possono essere specificati L'argomento facoltativo
|
| deprecate<T>(T, string, string) | Il metodo
Quando viene chiamato, Se lo stesso
Se vengono utilizzati i flag della riga di comando Se vengono impostati i flag Se il flag della riga di comando Il flag della riga di comando |
| diff(string | (readonly string[]), string | (readonly string[])) |
Se i valori sono uguali, viene restituita una matrice vuota.
|
| find<T>((x: T) => boolean, T[]) | Trova il primo valore in una matrice che corrisponde al predicato specificato. |
| find |
Trova l'indice del primo valore in una matrice che corrisponde al predicato specificato. |
| format(any, any[]) | Il metodo Se un identificatore non dispone di un argomento corrispondente, non viene sostituito:
I valori che non fanno parte della stringa di formato vengono formattati usando Se sono presenti più argomenti passati al metodo
Se il primo argomento non contiene un identificatore di formato valido,
Se viene passato un solo argomento a
|
| format |
Questa funzione è identica a formato, ad eccezione del fatto che accetta un argomento
|
| generateUUID() | Genera un uuid di 20 caratteri. |
| get |
|
| get |
Restituisce una matrice di oggetti sito di chiamata contenenti lo stack della funzione chiamante.
È possibile ricostruire le posizioni originali impostando l'opzione
|
| get |
Restituisce un numero casuale |
| get |
Restituisce una mappa di tutti i codici di errore di sistema disponibili nell'API Node.js.
Il mapping tra i codici di errore e i nomi degli errori è dipendente dalla piattaforma.
Vedere
|
| get |
Restituisce il messaggio stringa per un codice di errore numerico proveniente da un'API Node.js. Il mapping tra i codici di errore e i messaggi stringa è dipendente dalla piattaforma.
|
| get |
Restituisce il nome della stringa per un codice di errore numerico proveniente da un'API Node.js.
Il mapping tra i codici di errore e i nomi degli errori è dipendente dalla piattaforma.
Vedere
|
| get |
Restituisce l'intervallo di tempo tra due date in millisecondi |
| inherits(unknown, unknown) | L'utilizzo di Ereditare i metodi prototipo da un costruttore in un altro. Il prototipo di In questo modo viene aggiunta principalmente una convalida di input all'inizio di
Esempio di ES6 che usa
|
| inspect(any, boolean, null | number, boolean) | Il metodo
I riferimenti circolari puntano al relativo ancoraggio usando un indice di riferimento:
Nell'esempio seguente vengono esaminate tutte le proprietà dell'oggetto
Nell'esempio seguente viene evidenziato l'effetto dell'opzione
L'opzione
L'opzione
L'opzione
|
| inspect(any, Inspect |
|
| is |
Alias per Restituisce
|
| is |
Controlla se il tipo di incorporamento è per la creazione |
| is |
Restituisce Per altre informazioni sull'uguaglianza assoluta, vedere |
| is |
Controlla se l'URL di incorporamento è per il report RDL. |
| is |
Controlla se il report viene salvato. |
| parse |
Fornisce un'API di livello superiore per l'analisi degli argomenti della riga di comando rispetto all'interazione diretta con
|
| parse |
Stabilità: 1.1 - Sviluppo attivo Dato un esempio
|
| promisify((callback: (err?: any) => void) => void) | |
| promisify(Function) | |
| promisify<T1, T2, T3, T4, T5, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void) | |
| promisify<T1, T2, T3, T4, T5>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void) | |
| promisify<T1, T2, T3, T4, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void) | |
| promisify<T1, T2, T3, T4>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void) | |
| promisify<T1, T2, T3, TResult>((arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void) | |
| promisify<T1, T2, T3>((arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void) | |
| promisify<T1, T2, TResult>((arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void) | |
| promisify<T1, T2>((arg1: T1, arg2: T2, callback: (err?: any) => void) => void) | |
| promisify<T1, TResult>((arg1: T1, callback: (err: any, result: TResult) => void) => void) | |
| promisify<T1>((arg1: T1, callback: (err?: any) => void) => void) | |
| promisify<TCustom>(Custom |
Accetta una funzione che segue lo stile di callback di primo errore comune, ovvero l'acquisizione di un callback
In alternativa, usando in modo equivalente
Se è presente una
L'uso di
|
| promisify<TResult>((callback: (err: any, result: TResult) => void) => void) | |
| raise |
Genera un evento personalizzato con i dati dell'evento nell'elemento HTML specificato. |
| remove<T>((x: T) => boolean, T[]) | |
| set |
Abilitare o disabilitare la stampa di un'analisi dello stack in |
| strip |
Restituisce
|
| style |
Questa funzione restituisce un testo formattato considerando l'oggetto passato per la
Quando si passa una matrice di formati, l'ordine del formato applicato viene lasciato a destra in modo che lo stile seguente possa sovrascrivere quello precedente.
Il valore L'elenco completo dei formati è disponibile in modificatori. |
| to |
Restituisce il |
| transferable |
Crea e restituisce un'istanza di |
| transferable |
Contrassegna il
|
Dettagli funzione
aborted(AbortSignal, any)
È in ascolto dell'evento di interruzione nel signal fornito e restituisce una promessa che viene risolta quando il signal viene interrotto.
Se viene specificato resource, fa riferimento debole all'oggetto associato dell'operazione, quindi se resource viene sottoposto a Garbage Collection prima dell'interruzione del signal, la promessa restituita rimarrà in sospeso.
In questo modo si evitano perdite di memoria in operazioni con esecuzione prolungata o non annullabili.
import { aborted } from 'node:util';
// Obtain an object with an abortable signal, like a custom resource or operation.
const dependent = obtainSomethingAbortable();
// Pass `dependent` as the resource, indicating the promise should only resolve
// if `dependent` is still in memory when the signal is aborted.
aborted(dependent.signal, dependent).then(() => {
// This code runs when `dependent` is aborted.
console.log('Dependent resource was aborted.');
});
// Simulate an event that triggers the abort.
dependent.on('event', () => {
dependent.abort(); // This will cause the `aborted` promise to resolve.
});
function aborted(signal: AbortSignal, resource: any): Promise<void>
Parametri
- signal
-
AbortSignal
- resource
-
any
Qualsiasi oggetto non Null associato all'operazione interrotta e mantenuto debole.
Se resource viene sottoposto a Garbage Collection prima dell'interruzione del signal, la promessa rimane in sospeso, consentendo Node.js di interrompere il rilevamento.
Ciò consente di evitare perdite di memoria in operazioni con esecuzione prolungata o non annullabili.
Restituisce
Promise<void>
addParamToUrl(string, string, string)
Aggiunge un parametro all'URL specificato
function addParamToUrl(url: string, paramName: string, value: string): string
Parametri
- url
-
string
- paramName
-
string
- value
-
string
Restituisce
string
assign(any[])
Copia i valori di tutte le proprietà enumerabili da uno o più oggetti di origine a un oggetto di destinazione e restituisce l'oggetto di destinazione.
function assign(args: any[]): any
Parametri
- args
-
any[]
Restituisce
any
autoAuthInEmbedUrl(string)
Controlla se l'URL di incorporamento contiene autoAuth=true.
function autoAuthInEmbedUrl(embedUrl: string): boolean
Parametri
- embedUrl
-
string
Restituisce
boolean
callbackify(() => Promise<void>)
Accetta una funzione async (o una funzione che restituisce un Promise) e restituisce una funzione dopo lo stile di callback error-first, ovvero accettando un callback (err, value) => ... come ultimo argomento. Nel callback il primo argomento sarà il motivo del rifiuto (o null se il Promise risolto) e il secondo argomento sarà il valore risolto.
import { callbackify } from 'node:util';
async function fn() {
return 'hello world';
}
const callbackFunction = callbackify(fn);
callbackFunction((err, ret) => {
if (err) throw err;
console.log(ret);
});
Stampa:
hello world
Il callback viene eseguito in modo asincrono e avrà un'analisi dello stack limitata.
Se il callback viene generato, il processo genererà un evento 'uncaughtException' e, se non gestito, verrà chiuso.
Poiché null ha un significato speciale come primo argomento di un callback, se una funzione di cui è stato eseguito il wrapping rifiuta un Promise con un valore non valido come motivo, il valore viene incluso in un Error con il valore originale archiviato in un campo denominato reason.
function fn() {
return Promise.reject(null);
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
// When the Promise was rejected with `null` it is wrapped with an Error and
// the original value is stored in `reason`.
err && Object.hasOwn(err, 'reason') && err.reason === null; // true
});
function callbackify(fn: () => Promise<void>): (callback: (err: NodeJS.ErrnoException) => void) => void
Parametri
- fn
-
() => Promise<void>
Funzione async
Restituisce
(callback: (err: NodeJS.ErrnoException) => void) => void
una funzione di stile callback
callbackify<T1, T2, T3, T4, T5, T6, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult>)
function callbackify<T1, T2, T3, T4, T5, T6, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult>
Restituisce
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
callbackify<T1, T2, T3, T4, T5, T6>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>)
function callbackify<T1, T2, T3, T4, T5, T6>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>
Restituisce
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<T1, T2, T3, T4, T5, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>)
function callbackify<T1, T2, T3, T4, T5, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>
Restituisce
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
callbackify<T1, T2, T3, T4, T5>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>)
function callbackify<T1, T2, T3, T4, T5>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>
Restituisce
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<T1, T2, T3, T4, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>)
function callbackify<T1, T2, T3, T4, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>
Restituisce
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
callbackify<T1, T2, T3, T4>((arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>)
function callbackify<T1, T2, T3, T4>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>
Restituisce
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<T1, T2, T3, TResult>((arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>)
function callbackify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>
Restituisce
(arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
callbackify<T1, T2, T3>((arg1: T1, arg2: T2, arg3: T3) => Promise<void>)
function callbackify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3) => Promise<void>
Restituisce
(arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<T1, T2, TResult>((arg1: T1, arg2: T2) => Promise<TResult>)
function callbackify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2) => Promise<TResult>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
Parametri
- fn
-
(arg1: T1, arg2: T2) => Promise<TResult>
Restituisce
(arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void
callbackify<T1, T2>((arg1: T1, arg2: T2) => Promise<void>)
function callbackify<T1, T2>(fn: (arg1: T1, arg2: T2) => Promise<void>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void
Parametri
- fn
-
(arg1: T1, arg2: T2) => Promise<void>
Restituisce
(arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<T1, TResult>((arg1: T1) => Promise<TResult>)
function callbackify<T1, TResult>(fn: (arg1: T1) => Promise<TResult>): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void
Parametri
- fn
-
(arg1: T1) => Promise<TResult>
Restituisce
(arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void
callbackify<T1>((arg1: T1) => Promise<void>)
function callbackify<T1>(fn: (arg1: T1) => Promise<void>): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void
Parametri
- fn
-
(arg1: T1) => Promise<void>
Restituisce
(arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void
callbackify<TResult>(() => Promise<TResult>)
function callbackify<TResult>(fn: () => Promise<TResult>): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void
Parametri
- fn
-
() => Promise<TResult>
Restituisce
(callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void
createRandomString()
Genera una stringa di caratteri da 5 a 6 casuali.
function createRandomString(): string
Restituisce
string
debuglog(string, (fn: DebugLoggerFunction) => void)
Il util.debuglog() metodo viene usato per creare una funzione che scrive in modo condizionale i messaggi di debug in stderr in base all'esistenza della NODE_DEBUG variabile di ambiente. Se il nome section viene visualizzato all'interno del valore della variabile di ambiente, la funzione restituita funziona in modo simile a console.error(). In caso contrario, la funzione restituita è un no-op.
import { debuglog } from 'node:util';
const log = debuglog('foo');
log('hello from foo [%d]', 123);
Se questo programma viene eseguito con NODE_DEBUG=foo nell'ambiente, verrà restituito un risultato simile al seguente:
FOO 3245: hello from foo [123]
dove 3245 è l'ID processo. Se non viene eseguito con tale set di variabili di ambiente, non verrà stampato nulla.
Il section supporta anche i caratteri jolly:
import { debuglog } from 'node:util';
const log = debuglog('foo');
log('hi there, it\'s foo-bar [%d]', 2333);
se viene eseguito con NODE_DEBUG=foo* nell'ambiente, l'output sarà simile al seguente:
FOO-BAR 3257: hi there, it's foo-bar [2333]
Nella variabile di ambiente possono essere specificati section più nomi delimitati da NODE_DEBUG virgole: NODE_DEBUG=fs,net,tls.
L'argomento facoltativo callback può essere usato per sostituire la funzione di registrazione con una funzione diversa che non dispone di inizializzazione o wrapping non necessario.
import { debuglog } from 'node:util';
let log = debuglog('internals', (debug) => {
// Replace with a logging function that optimizes out
// testing if the section is enabled
log = debug;
});
function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger
Parametri
- section
-
string
Stringa che identifica la parte dell'applicazione per cui viene creata la funzione debuglog.
- callback
-
(fn: DebugLoggerFunction) => void
Un callback richiamato la prima volta che viene chiamata la funzione di registrazione con un argomento di funzione che è una funzione di registrazione più ottimizzata.
Restituisce
Funzione di registrazione
deprecate<T>(T, string, string)
Il metodo util.deprecate() esegue il wrapping di fn (che può essere una funzione o una classe) in modo che sia contrassegnato come deprecato.
import { deprecate } from 'node:util';
export const obsoleteFunction = deprecate(() => {
// Do something here.
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
Quando viene chiamato, util.deprecate() restituirà una funzione che genererà un DeprecationWarning usando l'evento 'warning'. L'avviso verrà generato e stampato in stderr la prima volta che viene chiamata la funzione restituita. Dopo l'emissione dell'avviso, la funzione di cui è stato eseguito il wrapping viene chiamata senza generare un avviso.
Se lo stesso code facoltativo viene fornito in più chiamate a util.deprecate(), l'avviso verrà generato una sola volta per tale code.
import { deprecate } from 'node:util';
const fn1 = deprecate(
() => 'a value',
'deprecation message',
'DEP0001',
);
const fn2 = deprecate(
() => 'a different value',
'other dep message',
'DEP0001',
);
fn1(); // Emits a deprecation warning with code DEP0001
fn2(); // Does not emit a deprecation warning because it has the same code
Se vengono utilizzati i flag della riga di comando --no-deprecation o --no-warnings o se la proprietà process.noDeprecation è impostata su trueprima al primo avviso di deprecazione, il metodo util.deprecate() non esegue alcuna operazione.
Se vengono impostati i flag --trace-deprecation o --trace-warnings della riga di comando oppure la proprietà process.traceDeprecation è impostata su true, viene stampato un avviso e un'analisi dello stack per stderr la prima chiamata della funzione deprecata.
Se il flag della riga di comando --throw-deprecation è impostato o la proprietà process.throwDeprecation è impostata su true, verrà generata un'eccezione quando viene chiamata la funzione deprecata.
Il flag della riga di comando --throw-deprecation e la proprietà process.throwDeprecation hanno la precedenza su --trace-deprecation e process.traceDeprecation.
function deprecate<T>(fn: T, msg: string, code?: string): T
Parametri
- fn
-
T
Funzione deprecata.
- msg
-
string
Messaggio di avviso da visualizzare quando viene richiamata la funzione deprecata.
- code
-
string
Codice deprecato. Per un elenco di codici, vedere il list of deprecated APIs.
Restituisce
T
Funzione deprecata di cui è stato eseguito il wrapping per generare un avviso.
diff(string | (readonly string[]), string | (readonly string[]))
util.diff() confronta due valori stringa o matrice e restituisce una matrice di voci di differenza.
Usa l'algoritmo diff myers per calcolare le differenze minime, ovvero lo stesso algoritmo usato internamente dai messaggi di errore dell'asserzione.
Se i valori sono uguali, viene restituita una matrice vuota.
const { diff } = require('node:util');
// Comparing strings
const actualString = '12345678';
const expectedString = '12!!5!7!';
console.log(diff(actualString, expectedString));
// [
// [0, '1'],
// [0, '2'],
// [1, '3'],
// [1, '4'],
// [-1, '!'],
// [-1, '!'],
// [0, '5'],
// [1, '6'],
// [-1, '!'],
// [0, '7'],
// [1, '8'],
// [-1, '!'],
// ]
// Comparing arrays
const actualArray = ['1', '2', '3'];
const expectedArray = ['1', '3', '4'];
console.log(diff(actualArray, expectedArray));
// [
// [0, '1'],
// [1, '2'],
// [0, '3'],
// [-1, '4'],
// ]
// Equal values return empty array
console.log(diff('same', 'same'));
// []
function diff(actual: string | (readonly string[]), expected: string | (readonly string[])): DiffEntry[]
Parametri
- actual
-
string | (readonly string[])
Primo valore da confrontare
- expected
-
string | (readonly string[])
Secondo valore da confrontare
Restituisce
Matrice di voci di differenza. Ogni voce è una matrice con due elementi:
- Indice 0:
numbercodice operazione:-1per l'eliminazione,0per no-op/unchanged,1per l'inserimento - Indice 1:
stringvalore associato all'operazione
find<T>((x: T) => boolean, T[])
Trova il primo valore in una matrice che corrisponde al predicato specificato.
function find<T>(predicate: (x: T) => boolean, xs: T[]): T
Parametri
- predicate
-
(x: T) => boolean
- xs
-
T[]
Restituisce
T
findIndex<T>((x: T) => boolean, T[])
Trova l'indice del primo valore in una matrice che corrisponde al predicato specificato.
function findIndex<T>(predicate: (x: T) => boolean, xs: T[]): number
Parametri
- predicate
-
(x: T) => boolean
- xs
-
T[]
Restituisce
number
format(any, any[])
Il metodo util.format() restituisce una stringa formattata usando il primo argomento come stringa di formato di printfche può contenere zero o più identificatori di formato. Ogni identificatore viene sostituito con il valore convertito dall'argomento corrispondente. Gli identificatori supportati sono:
Se un identificatore non dispone di un argomento corrispondente, non viene sostituito:
util.format('%s:%s', 'foo');
// Returns: 'foo:%s'
I valori che non fanno parte della stringa di formato vengono formattati usando util.inspect() se il tipo non è string.
Se sono presenti più argomenti passati al metodo util.format() rispetto al numero di identificatori, gli argomenti aggiuntivi vengono concatenati alla stringa restituita, separati da spazi:
util.format('%s:%s', 'foo', 'bar', 'baz');
// Returns: 'foo:bar baz'
Se il primo argomento non contiene un identificatore di formato valido, util.format() restituisce una stringa che rappresenta la concatenazione di tutti gli argomenti separati da spazi:
util.format(1, 2, 3);
// Returns: '1 2 3'
Se viene passato un solo argomento a util.format(), viene restituito così come è senza formattazione:
util.format('%% %s');
// Returns: '%% %s'
util.format() è un metodo sincrono destinato a uno strumento di debug.
Alcuni valori di input possono avere un sovraccarico significativo delle prestazioni che può bloccare il ciclo di eventi. Usare questa funzione con attenzione e mai in un percorso di codice frequente.
function format(format?: any, param: any[]): string
Parametri
- format
-
any
Stringa di formato printf.
- param
-
any[]
Restituisce
string
formatWithOptions(InspectOptions, any, any[])
Questa funzione è identica a formato, ad eccezione del fatto che accetta un argomento inspectOptions che specifica le opzioni passate a ispezionare.
util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
// Returns 'See object { foo: 42 }', where `42` is colored as a number
// when printed to a terminal.
function formatWithOptions(inspectOptions: InspectOptions, format?: any, param: any[]): string
Parametri
- inspectOptions
- InspectOptions
- format
-
any
- param
-
any[]
Restituisce
string
generateUUID()
Genera un uuid di 20 caratteri.
function generateUUID(): string
Restituisce
string
getCallSites(GetCallSitesOptions)
function getCallSites(options: GetCallSitesOptions): CallSiteObject[]
Parametri
- options
-
GetCallSitesOptions
Restituisce
getCallSites(number, GetCallSitesOptions)
Restituisce una matrice di oggetti sito di chiamata contenenti lo stack della funzione chiamante.
import { getCallSites } from 'node:util';
function exampleFunction() {
const callSites = getCallSites();
console.log('Call Sites:');
callSites.forEach((callSite, index) => {
console.log(`CallSite ${index + 1}:`);
console.log(`Function Name: ${callSite.functionName}`);
console.log(`Script Name: ${callSite.scriptName}`);
console.log(`Line Number: ${callSite.lineNumber}`);
console.log(`Column Number: ${callSite.column}`);
});
// CallSite 1:
// Function Name: exampleFunction
// Script Name: /home/example.js
// Line Number: 5
// Column Number: 26
// CallSite 2:
// Function Name: anotherFunction
// Script Name: /home/example.js
// Line Number: 22
// Column Number: 3
// ...
}
// A function to simulate another stack layer
function anotherFunction() {
exampleFunction();
}
anotherFunction();
È possibile ricostruire le posizioni originali impostando l'opzione sourceMap su true.
Se la mappa di origine non è disponibile, la posizione originale sarà la stessa della posizione corrente.
Quando il flag --enable-source-maps è abilitato, ad esempio quando si usa --experimental-transform-types, sourceMap sarà true per impostazione predefinita.
import { getCallSites } from 'node:util';
interface Foo {
foo: string;
}
const callSites = getCallSites({ sourceMap: true });
// With sourceMap:
// Function Name: ''
// Script Name: example.js
// Line Number: 7
// Column Number: 26
// Without sourceMap:
// Function Name: ''
// Script Name: example.js
// Line Number: 2
// Column Number: 26
function getCallSites(frameCount?: number, options?: GetCallSitesOptions): CallSiteObject[]
Parametri
- frameCount
-
number
Numero di frame da acquisire come oggetti del sito di chiamata.
valore predefinito:10. L'intervallo consentito è compreso tra 1 e 200.
- options
-
GetCallSitesOptions
Restituisce
Matrice di oggetti sito di chiamata
getRandomValue()
Restituisce un numero casuale
function getRandomValue(): number
Restituisce
number
getSystemErrorMap()
Restituisce una mappa di tutti i codici di errore di sistema disponibili nell'API Node.js.
Il mapping tra i codici di errore e i nomi degli errori è dipendente dalla piattaforma.
Vedere Common System Errors per i nomi degli errori comuni.
fs.access('file/that/does/not/exist', (err) => {
const errorMap = util.getSystemErrorMap();
const name = errorMap.get(err.errno);
console.error(name); // ENOENT
});
function getSystemErrorMap(): Map<number, [string, string]>
Restituisce
Map<number, [string, string]>
getSystemErrorMessage(number)
Restituisce il messaggio stringa per un codice di errore numerico proveniente da un'API Node.js. Il mapping tra i codici di errore e i messaggi stringa è dipendente dalla piattaforma.
fs.access('file/that/does/not/exist', (err) => {
const message = util.getSystemErrorMessage(err.errno);
console.error(message); // no such file or directory
});
function getSystemErrorMessage(err: number): string
Parametri
- err
-
number
Restituisce
string
getSystemErrorName(number)
Restituisce il nome della stringa per un codice di errore numerico proveniente da un'API Node.js.
Il mapping tra i codici di errore e i nomi degli errori è dipendente dalla piattaforma.
Vedere Common System Errors per i nomi degli errori comuni.
fs.access('file/that/does/not/exist', (err) => {
const name = util.getSystemErrorName(err.errno);
console.error(name); // ENOENT
});
function getSystemErrorName(err: number): string
Parametri
- err
-
number
Restituisce
string
getTimeDiffInMilliseconds(Date, Date)
Restituisce l'intervallo di tempo tra due date in millisecondi
function getTimeDiffInMilliseconds(start: Date, end: Date): number
Parametri
- start
-
Date
- end
-
Date
Restituisce
number
inherits(unknown, unknown)
L'utilizzo di util.inherits() è sconsigliato. Usare le parole chiave ES6 class e extends per ottenere il supporto dell'ereditarietà a livello di linguaggio. Si noti anche che i due stili sono semanticamente incompatibili.
Ereditare i metodi prototipo da un costruttore in un altro. Il prototipo di constructor verrà impostato su un nuovo oggetto creato da superConstructor.
In questo modo viene aggiunta principalmente una convalida di input all'inizio di Object.setPrototypeOf(constructor.prototype, superConstructor.prototype).
Per comodità aggiuntiva, superConstructor sarà accessibile tramite la proprietà constructor.super_.
const util = require('node:util');
const EventEmitter = require('node:events');
function MyStream() {
EventEmitter.call(this);
}
util.inherits(MyStream, EventEmitter);
MyStream.prototype.write = function(data) {
this.emit('data', data);
};
const stream = new MyStream();
console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('It works!'); // Received data: "It works!"
Esempio di ES6 che usa class e extends:
import EventEmitter from 'node:events';
class MyStream extends EventEmitter {
write(data) {
this.emit('data', data);
}
}
const stream = new MyStream();
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('With ES6');
function inherits(constructor: unknown, superConstructor: unknown)
Parametri
- constructor
-
unknown
- superConstructor
-
unknown
inspect(any, boolean, null | number, boolean)
Il metodo util.inspect() restituisce una rappresentazione di stringa di object destinata al debug. L'output di util.inspect può cambiare in qualsiasi momento e non deve dipendere a livello di codice. È possibile passare options aggiuntivi che modificano il risultato.
util.inspect() userà il nome e/o Symbol.toStringTag la proprietà del costruttore per rendere un tag identificabile per un valore ispezionato.
class Foo {
get [Symbol.toStringTag]() {
return 'bar';
}
}
class Bar {}
const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
util.inspect(new Foo()); // 'Foo [bar] {}'
util.inspect(new Bar()); // 'Bar {}'
util.inspect(baz); // '[foo] {}'
I riferimenti circolari puntano al relativo ancoraggio usando un indice di riferimento:
import { inspect } from 'node:util';
const obj = {};
obj.a = [obj];
obj.b = {};
obj.b.inner = obj.b;
obj.b.obj = obj;
console.log(inspect(obj));
// <ref *1> {
// a: [ [Circular *1] ],
// b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
// }
Nell'esempio seguente vengono esaminate tutte le proprietà dell'oggetto util:
import util from 'node:util';
console.log(util.inspect(util, { showHidden: true, depth: null }));
Nell'esempio seguente viene evidenziato l'effetto dell'opzione compact:
import { inspect } from 'node:util';
const o = {
a: [1, 2, [[
'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' +
'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
'test',
'foo']], 4],
b: new Map([['za', 1], ['zb', 'test']]),
};
console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 }));
// { a:
// [ 1,
// 2,
// [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line
// 'test',
// 'foo' ] ],
// 4 ],
// b: Map(2) { 'za' => 1, 'zb' => 'test' } }
// Setting `compact` to false or an integer creates more reader friendly output.
console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 }));
// {
// a: [
// 1,
// 2,
// [
// [
// 'Lorem ipsum dolor sit amet,\n' +
// 'consectetur adipiscing elit, sed do eiusmod \n' +
// 'tempor incididunt ut labore et dolore magna aliqua.',
// 'test',
// 'foo'
// ]
// ],
// 4
// ],
// b: Map(2) {
// 'za' => 1,
// 'zb' => 'test'
// }
// }
// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
// single line.
L'opzione showHidden consente di controllare WeakMap e WeakSet voci. Se sono presenti più voci di maxArrayLength, non esiste alcuna garanzia per quali voci vengono visualizzate. Ciò significa che il recupero delle stesse voci WeakSet due volte può comportare un output diverso. Inoltre, le voci senza riferimenti sicuri rimanenti possono essere raccolte in qualsiasi momento.
import { inspect } from 'node:util';
const obj = { a: 1 };
const obj2 = { b: 2 };
const weakSet = new WeakSet([obj, obj2]);
console.log(inspect(weakSet, { showHidden: true }));
// WeakSet { { a: 1 }, { b: 2 } }
L'opzione sorted assicura che l'ordine di inserimento delle proprietà di un oggetto non influisca sul risultato di util.inspect().
import { inspect } from 'node:util';
import assert from 'node:assert';
const o1 = {
b: [2, 3, 1],
a: '`a` comes before `b`',
c: new Set([2, 3, 1]),
};
console.log(inspect(o1, { sorted: true }));
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
const o2 = {
c: new Set([2, 1, 3]),
a: '`a` comes before `b`',
b: [2, 3, 1],
};
assert.strict.equal(
inspect(o1, { sorted: true }),
inspect(o2, { sorted: true }),
);
L'opzione numericSeparator aggiunge un carattere di sottolineatura ogni tre cifre a tutti i numeri.
import { inspect } from 'node:util';
const thousand = 1000;
const million = 1000000;
const bigNumber = 123456789n;
const bigDecimal = 1234.12345;
console.log(inspect(thousand, { numericSeparator: true }));
// 1_000
console.log(inspect(million, { numericSeparator: true }));
// 1_000_000
console.log(inspect(bigNumber, { numericSeparator: true }));
// 123_456_789n
console.log(inspect(bigDecimal, { numericSeparator: true }));
// 1_234.123_45
util.inspect() è un metodo sincrono destinato al debug. La lunghezza massima dell'output è di circa 128 MiB. Gli input che generano un output più lungo verranno troncati.
function inspect(object: any, showHidden?: boolean, depth?: null | number, color?: boolean): string
Parametri
- object
-
any
Qualsiasi primitiva JavaScript o Object.
- showHidden
-
boolean
- depth
-
null | number
- color
-
boolean
Restituisce
string
Rappresentazione di object.
inspect(any, InspectOptions)
function inspect(object: any, options?: InspectOptions): string
Parametri
- object
-
any
- options
- InspectOptions
Restituisce
string
isArray(unknown)
Avviso
Questa API è ora deprecata.
Since v4.0.0 - Use isArray instead.
Alias per Array.isArray().
Restituisce true se il object specificato è un Array. In caso contrario, restituisce false.
import util from 'node:util';
util.isArray([]);
// Returns: true
util.isArray(new Array());
// Returns: true
util.isArray({});
// Returns: false
function isArray(object: unknown): object
Parametri
- object
-
unknown
Restituisce
object
isCreate(string)
Controlla se il tipo di incorporamento è per la creazione
function isCreate(embedType: string): boolean
Parametri
- embedType
-
string
Restituisce
boolean
isDeepStrictEqual(unknown, unknown, IsDeepStrictEqualOptions)
Restituisce true se esiste un'uguaglianza assoluta tra val1 e val2.
In caso contrario, restituisce false.
Per altre informazioni sull'uguaglianza assoluta, vedere assert.deepStrictEqual().
function isDeepStrictEqual(val1: unknown, val2: unknown, options?: IsDeepStrictEqualOptions): boolean
Parametri
- val1
-
unknown
- val2
-
unknown
- options
- IsDeepStrictEqualOptions
Restituisce
boolean
isRDLEmbed(string)
Controlla se l'URL di incorporamento è per il report RDL.
function isRDLEmbed(embedUrl: string): boolean
Parametri
- embedUrl
-
string
Restituisce
boolean
isSavedInternal(HttpPostMessage, string, Window)
Controlla se il report viene salvato.
function isSavedInternal(hpm: HttpPostMessage, uid: string, contentWindow: Window): Promise<boolean>
Parametri
- hpm
-
HttpPostMessage
- uid
-
string
- contentWindow
-
Window
Restituisce
Promise<boolean>
parseArgs<T>(T)
Fornisce un'API di livello superiore per l'analisi degli argomenti della riga di comando rispetto all'interazione diretta con process.argv. Accetta una specifica per gli argomenti previsti e restituisce un oggetto strutturato con le opzioni analizzate e i posizionali.
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f',
},
bar: {
type: 'string',
},
};
const {
values,
positionals,
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
function parseArgs<T>(config?: T): ParsedResults<T>
Parametri
- config
-
T
Usato per fornire argomenti per l'analisi e per configurare il parser.
config supporta le proprietà seguenti:
Restituisce
ParsedResults<T>
Argomenti della riga di comando analizzati:
parseEnv(string)
Stabilità: 1.1 - Sviluppo attivo Dato un esempio .env file:
import { parseEnv } from 'node:util';
parseEnv('HELLO=world\nHELLO=oh my\n');
// Returns: { HELLO: 'oh my' }
function parseEnv(content: string): NodeJS.Dict<string>
Parametri
- content
-
string
Contenuto non elaborato di un file .env.
Restituisce
NodeJS.Dict<string>
promisify((callback: (err?: any) => void) => void)
function promisify(fn: (callback: (err?: any) => void) => void): () => Promise<void>
Parametri
- fn
-
(callback: (err?: any) => void) => void
Restituisce
() => Promise<void>
promisify(Function)
function promisify(fn: Function): Function
Parametri
- fn
-
Function
Restituisce
Function
promisify<T1, T2, T3, T4, T5, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void)
function promisify<T1, T2, T3, T4, T5, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void
Restituisce
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>
promisify<T1, T2, T3, T4, T5>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void)
function promisify<T1, T2, T3, T4, T5>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void
Restituisce
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>
promisify<T1, T2, T3, T4, TResult>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void)
function promisify<T1, T2, T3, T4, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void
Restituisce
(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>
promisify<T1, T2, T3, T4>((arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void)
function promisify<T1, T2, T3, T4>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void
Restituisce
(arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>
promisify<T1, T2, T3, TResult>((arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void)
function promisify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void
Restituisce
(arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>
promisify<T1, T2, T3>((arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void)
function promisify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise<void>
Parametri
- fn
-
(arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void
Restituisce
(arg1: T1, arg2: T2, arg3: T3) => Promise<void>
promisify<T1, T2, TResult>((arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void)
function promisify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise<TResult>
Parametri
- fn
-
(arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void
Restituisce
(arg1: T1, arg2: T2) => Promise<TResult>
promisify<T1, T2>((arg1: T1, arg2: T2, callback: (err?: any) => void) => void)
function promisify<T1, T2>(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise<void>
Parametri
- fn
-
(arg1: T1, arg2: T2, callback: (err?: any) => void) => void
Restituisce
(arg1: T1, arg2: T2) => Promise<void>
promisify<T1, TResult>((arg1: T1, callback: (err: any, result: TResult) => void) => void)
function promisify<T1, TResult>(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise<TResult>
Parametri
- fn
-
(arg1: T1, callback: (err: any, result: TResult) => void) => void
Restituisce
(arg1: T1) => Promise<TResult>
promisify<T1>((arg1: T1, callback: (err?: any) => void) => void)
function promisify<T1>(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise<void>
Parametri
- fn
-
(arg1: T1, callback: (err?: any) => void) => void
Restituisce
(arg1: T1) => Promise<void>
promisify<TCustom>(CustomPromisify<TCustom>)
Accetta una funzione che segue lo stile di callback di primo errore comune, ovvero l'acquisizione di un callback (err, value) => ... come ultimo argomento e restituisce una versione che restituisce promesse.
import { promisify } from 'node:util';
import { stat } from 'node:fs';
const promisifiedStat = promisify(stat);
promisifiedStat('.').then((stats) => {
// Do something with `stats`
}).catch((error) => {
// Handle the error.
});
In alternativa, usando in modo equivalente async functions:
import { promisify } from 'node:util';
import { stat } from 'node:fs';
const promisifiedStat = promisify(stat);
async function callStat() {
const stats = await promisifiedStat('.');
console.log(`This directory is owned by ${stats.uid}`);
}
callStat();
Se è presente una original[util.promisify.custom] proprietà, promisify restituirà il relativo valore, vedere Funzioni promisificate personalizzate.
promisify() presuppone che original sia una funzione che accetta un callback come argomento finale in tutti i casi. Se original non è una funzione, promisify() genererà un errore. Se original è una funzione ma l'ultimo argomento non è un callback di tipo error-first, verrà comunque passato un callback error-first come ultimo argomento.
L'uso di promisify() su metodi di classe o altri metodi che usano this potrebbe non funzionare come previsto, a meno che non venga gestito in modo speciale:
import { promisify } from 'node:util';
class Foo {
constructor() {
this.a = 42;
}
bar(callback) {
callback(null, this.a);
}
}
const foo = new Foo();
const naiveBar = promisify(foo.bar);
// TypeError: Cannot read properties of undefined (reading 'a')
// naiveBar().then(a => console.log(a));
naiveBar.call(foo).then((a) => console.log(a)); // '42'
const bindBar = naiveBar.bind(foo);
bindBar().then((a) => console.log(a)); // '42'
function promisify<TCustom>(fn: CustomPromisify<TCustom>): TCustom
Parametri
- fn
-
CustomPromisify<TCustom>
Restituisce
TCustom
promisify<TResult>((callback: (err: any, result: TResult) => void) => void)
function promisify<TResult>(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise<TResult>
Parametri
- fn
-
(callback: (err: any, result: TResult) => void) => void
Restituisce
() => Promise<TResult>
raiseCustomEvent(HTMLElement, string, any)
Genera un evento personalizzato con i dati dell'evento nell'elemento HTML specificato.
function raiseCustomEvent(element: HTMLElement, eventName: string, eventData: any)
Parametri
- element
-
HTMLElement
- eventName
-
string
- eventData
-
any
remove<T>((x: T) => boolean, T[])
function remove<T>(predicate: (x: T) => boolean, xs: T[])
Parametri
- predicate
-
(x: T) => boolean
- xs
-
T[]
setTraceSigInt(boolean)
Abilitare o disabilitare la stampa di un'analisi dello stack in SIGINT. L'API è disponibile solo nel thread principale.
function setTraceSigInt(enable: boolean)
Parametri
- enable
-
boolean
stripVTControlCharacters(string)
Restituisce str con eventuali codici di escape ANSI rimossi.
console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
// Prints "value"
function stripVTControlCharacters(str: string): string
Parametri
- str
-
string
Restituisce
string
styleText(ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], string, StyleTextOptions)
Questa funzione restituisce un testo formattato considerando l'oggetto passato per la format stampa in un terminale. È a conoscenza delle funzionalità del terminale e agisce in base alla configurazione impostata tramite NO_COLORle NODE_DISABLE_COLORS variabili di ambiente e FORCE_COLOR .
import { styleText } from 'node:util';
import { stderr } from 'node:process';
const successMessage = styleText('green', 'Success!');
console.log(successMessage);
const errorMessage = styleText(
'red',
'Error! Error!',
// Validate if process.stderr has TTY
{ stream: stderr },
);
console.error(errorMessage);
util.inspect.colors fornisce anche formati di testo come italice underline ed è possibile combinare entrambi:
console.log(
util.styleText(['underline', 'italic'], 'My italic underlined message'),
);
Quando si passa una matrice di formati, l'ordine del formato applicato viene lasciato a destra in modo che lo stile seguente possa sovrascrivere quello precedente.
console.log(
util.styleText(['red', 'green'], 'text'), // green
);
Il valore none di formato speciale non applica stili aggiuntivi al testo.
L'elenco completo dei formati è disponibile in modificatori.
function styleText(format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions): string
Parametri
- format
-
ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[]
Formato di testo o matrice di formati di testo definiti in util.inspect.colors.
- text
-
string
Testo da formattare.
- options
- StyleTextOptions
Restituisce
string
toUSVString(string)
Restituisce il string dopo aver sostituito qualsiasi punto di codice surrogato (o in modo equivalente, qualsiasi unità di codice surrogato non abbinato) con il carattere di sostituzione Unicode U+FFFD.
function toUSVString(string: string): string
Parametri
- string
-
string
Restituisce
string
transferableAbortController()
Crea e restituisce un'istanza di AbortController la cui AbortSignal è contrassegnata come trasferiscibile e può essere usata con structuredClone() o postMessage().
function transferableAbortController(): AbortController
Restituisce
AbortController
Un abortController trasferiscibile
transferableAbortSignal(AbortSignal)
Contrassegna il AbortSignal specificato come trasferiscibile in modo che possa essere usato constructuredClone() e postMessage().
const signal = transferableAbortSignal(AbortSignal.timeout(100));
const channel = new MessageChannel();
channel.port2.postMessage(signal, [signal]);
function transferableAbortSignal(signal: AbortSignal): AbortSignal
Parametri
- signal
-
AbortSignal
The AbortSignal
Restituisce
AbortSignal
Lo stesso abortSignal