Wednesday, 2 August 2017

Nodejs Buffer Binary Options


Armazenando dados com fluxos graváveis ​​Node. js Este tutorial explicará como armazenar dados com fluxos graváveis ​​Node. js e como criar seu próprio fluxo gravável personalizado. Informações sobre a versão Autor: Jeff Barczewski Publicado em: 18 de agosto de 2013 Tags: nodejs, streams Nível: Intermediário Pré-requisitos: buffers, eventos, instalar npm modules Node. js v0.10 (último estável é v0.10.16 até à data desta redação) Geralmente têm sido uma parte do Node. js desde seus primeiros dias Streams2 Writable classe abstrata pode ser usado com versões mais antigas (antes de v0.10) de nó usando o módulo npm readable-stream (testado com v1.0.15) Armazenando dados com gravável Córregos Escrever arquivo de texto O exemplo mais simples é apenas por escrito utf8 texto, uma vez que a codificação padrão se você escrever seqüências de caracteres é utf8. Se você quiser escrever seqüências de caracteres com uma codificação diferente, então você pode simplesmente alterar a linha createWriteStream ou adicionar codificação para cada gravação. Escrevendo arquivo binário Escrever um arquivo binário é apenas uma questão de usar Buffers em vez de seqüências de caracteres para a gravação. No exemplo acima, eu uso crypto. createRandomBytes () para criar um Buffer de dados, mas você pode usar dados binários que você cria ou lê de outra fonte tão facilmente. Saber quando arquivo foi escrito Entrada e saída são operações assíncronas em Node. js Então, o que se queremos saber quando um arquivo foi totalmente escrito A resposta é a configuração de ouvintes para eventos que o fluxo emite. O evento finish (adicionado em Node. js v0.10) indica que todos os dados foram liberados para o sistema subjacente. Em Node. js antes de v0.10, você poderia adicionar um cb para o. end () para obter uma indicação de quando que tinha sido liberado, no entanto terminar leva em conta quaisquer outras transformações a jusante e tal. Criando fluxos graváveis ​​Node. js personalizados Quando você precisa criar seu próprio fluxo gravável personalizado para armazenar dados em um banco de dados ou em outra facilidade de armazenamento, é fácil se você usar a nova classe abstrata de Streams2 Writable disponível nativamente em Node. js 0.10 ou via Npm polyfill módulo readable-stream. Para criar um fluxo gravável que implementa todo o comportamento de fluxo Node. js normal, você só tem que subclassar Writeable e implementar write (chunk, encoding, cb). Criando fluxo de memória gravável Aqui está um exemplo que está escrevendo em um armazenamento de dados simples na memória. Estamos usando o nome dado na criação do fluxo como a chave, e acrescentamos dados ao valor até terminar. Os fluxos graváveis ​​são elegantes e simples de usar. Escrever texto ou dados binários para fluxos Node. js é fácil, e até mesmo criar fluxos graváveis ​​personalizados totalmente funcionais é uma caminhada no parque com a nova funcionalidade streams2 introduzida em Node. js v0.10 (ou Utilizando o módulo de leitura de fluxo polifilho). Para leitura adicional Siga-me Compartilhar esta páginaNodeJS: Analisando o binário da camada TCP Para um trabalho recentemente, foi-me pedido para criar um servidor de bridge que traduzisse o protocolo de um antigo servidor legado para um novo cliente HTML5 e vice-versa. O protocolo antigo foi construído sobre estruturas C eo servidor estava se comunicando em binário na camada TCP. O novo cliente estará se comunicando em mensagens JSON via TCP sobre HTTP (também conhecido como soquetes web). NodeJS vem muito bem equipado com um módulo, net. Para comunica�o atrav� da camada TCP. Basta exigir (rede) e agora você está equipado para abrir um soquete TCP. O módulo vem com uma classe Socket, e novas conexões de soquete podem ser instanciadas quando necessário: NodeJS também possui uma classe Buffer. Que irá montar pacotes de dados binários brutos em um objeto tipo matriz que pode conter somente números inteiros. Uma instância da classe Buffer representa uma alocação de memória de tamanho fixo específico, fora da pilha V8. Eu usá-lo para coletar os pacotes de dados de entrada, bem como para montar corretamente meus dados binários de saída. O binário de entrada foi organizado como structs C, e eu sou capaz de analisar os dados com bastante facilidade usando uma grande biblioteca npm chamada node-struct. A biblioteca node-struct permite que o desenvolvedor defina as estruturas em termos de objetos javascript com campos estritamente digitados e pré-alocados. Existem tipos para palavras de 8 bits através de 32 bits, assinado e sem assinatura, grande e pequeno endian. Há também campos para ascii e outros caracteres codificados, bem como campos para outras estruturas em estruturas. Por exemplo: Uma vez que a estrutura foi semeada com o buffer binário, agora você pode acessar os valores dos pacotes binários, analisados ​​corretamente como campos na estrutura: Como você provavelmente pode ver, esta biblioteca nó-struct é uma ferramenta muito útil quando Trabalhando em NodeJS com fluxos binários que representam structs. Os dados são analisados ​​e estou pronto para começar a trabalhar com ele no meu aplicativo. Às vezes, eu só quero ver as matérias-primas entrar e sair. FWIW, heres como Im registrar meus fluxos binários de entrada e saída: Adam D Richman engenheiro de software Food-and-Music-loving Compartilhar esta postagem Todos os conteúdos refatoração de direitos autorais. Copy 2015 Todos os direitos reservados. Orgulhosamente publicado com GhostClass: binaryjs. BinaryServer Node. js only Esta classe é um servidor websocket BinaryJS. É um EventEmitter. New binaryjs. BinaryServer (opções, callback) opções Object host String. Padrão 0.0.0.0 porta Servidor de números Objeto. Use um http. Server existente ou ws. Server em vez de criar um novo. Caminho String. O caminho para aceitar as conexões do WebSocket chunkSize Number. Passado em construtor de conectar BinaryClient. Padrão 40960 Construir um novo objeto de servidor. Qualquer porta deve ser fornecida ou servidor para usar um http. Server existente. Um hash de todos os clientes conectados. As chaves são ids de cliente e os valores são instâncias de binaryjs. BinaryClient. Feche o servidor e encerre todos os clientes. Se o servidor subjacente emitir um erro, ele será encaminhado aqui. Quando uma nova conexão BinaryJS é estabelecida. Client é um objeto do tipo binaryjs. BinaryClient. Classe: binaryjs. BinaryClient Node. js e browsers Esta classe representa uma conexão de cliente websocket BinaryJS. É um EventEmitter. New binaryjs. BinaryClient (endereço, opções) Conecta-se ao endereço fornecido (no formato ws: // url). Opções Objeto chunkSize Number. Tamanho dos pedaços ao usar client. send. Padrão 40960 BinaryClient também pode ser obtido no evento de conexão de um BinaryServer Um hash de todos os fluxos atuais. As chaves são ids de fluxo e os valores são instâncias de binaryjs. BinaryStream. Cria um novo objeto binaryjs. BinaryStream legível e gravável, desencadeando um evento de fluxo no cliente remoto com o dado parâmetro de dados meta. Cria um novo objeto binaryjs. BinaryStream legível e gravável com os meta dados dados e envia dados através da conexão. Se os dados forem um Node. js Buffer ou ArrayBuffer do navegador. ArrayBufferView. Bolha. Ou Arquivo. Os dados serão fragmentados de acordo com options. chunkSize e transmitidos através do novo BinaryStream. Se dados são um fluxo Node. js (incluindo objetos BinaryStream), ele será canalizado para um novo BinaryStream Se os dados forem de qualquer outro tipo, ele será enviado através do fluxo em um pedaço. Fecha graciosamente a conexão. Function (stream, meta) Emitida quando um novo fluxo é inicializado pelo cliente remoto. Stream é um objeto binaryjs. BinaryStream que é tanto legível quanto gravável. Meta é o dado dado quando o fluxo foi criado via createStream (meta) ou send (data, meta). Enviado literalmente. Se o cliente emite um erro, este evento é emitido (erros do subjacente net. Socket são encaminhados aqui). É emitido quando a conexão é fechada. O evento close também é emitido quando, em seguida, net. Socket subjacente fecha a conexão (fim ou fechar). Emitido quando a conexão é estabelecida. Classe: binaryjs. BinaryStream Node. js e navegadores Esta classe representa um fluxo de cliente BinaryJS. É um Node. js Stream e EventEmitter. BinaryStreams são criados através do método createStream do BinaryClient e enviam métodos e recebidos através do evento de fluxo. Porque BinaryStream estende o fluxo Node. js. Todos os outros fluxos podem ser canalizados para ou a partir de um BinaryStream. O navegador implementa uma versão do navegador da API de fluxo Node. js. Um número de identificação identificando o fluxo. Único para o determinado cliente, mas não globalmente. Envia uma mensagem final, acionando o evento final e marca stream. readable false mas não fecha o socket. Retorna true se os dados forem escritos imediatamente ou false se os dados estiverem armazenados em buffer no socket. Grava dados através da conexão. Dados podem ser qualquer tipo compatível com JSON ou dados binários. Os dados de nota não serão fragmentados. Client. send deve ser usado para chunking. Feche imediatamente o soquete. Este é um método Stream. prototype disponível em todos os Streams. Node. js v6.7.0 Stream de Documentação Um fluxo é uma interface abstrata para trabalhar com dados de fluxo contínuo em Node. js. O módulo de fluxo fornece uma API base que facilita a criação de objetos que implementam a interface de fluxo. Há muitos objetos de fluxo fornecidos por Node. js. Por exemplo, uma solicitação para um servidor HTTP e process. stdout são ambas as instâncias de fluxo. Os fluxos podem ser legíveis, graváveis ​​ou ambos. Todos os streams são instâncias de EventEmitter. O módulo de fluxo pode ser acessado usando: Embora seja importante para todos os usuários do Node. js entender como os fluxos funcionam, o módulo de fluxo em si é mais útil para os desenvolvedores que estão criando novos tipos de instâncias de fluxo. Os desenvolvedores que consumam principalmente objetos de fluxo raramente terão necessidade de usar o módulo de fluxo diretamente. Organização deste documento Este documento é dividido em duas seções principais e terceira seção para notas adicionais. A primeira seção explica os elementos da API de fluxo que são necessários para usar fluxos dentro de um aplicativo. A segunda seção explica os elementos da API que são necessários para implementar novos tipos de fluxos. Tipos de Fluxos Existem quatro tipos de fluxos fundamentais dentro do Node. js: Readable - fluxos a partir dos quais os dados podem ser lidos (por exemplo fs. createReadStream ()). Gravável - fluxos aos quais os dados podem ser escritos (por exemplo fs. createWriteStream ()). Duplex - fluxos que são legíveis e graváveis ​​(por exemplo, net. Socket). Transformação - Fluxos duplex que podem modificar ou transformar os dados conforme são escritos e lidos (por exemplo, zlib. createDeflate ()). Modo Objeto Todos os fluxos criados pelas APIs Node. js operam exclusivamente em strings e objetos Buffer. No entanto, é possível que as implementações de fluxo funcionem com outros tipos de valores JavaScript (com exceção de null que serve a um propósito especial nos fluxos). Tais correntes são consideradas para operar no modo quotobject. As instâncias do fluxo são comutadas para o modo objeto usando a opção objectMode quando o fluxo é criado. A tentativa de mudar um fluxo existente para o modo de objeto não é segura. Buffering Ambos os fluxos graváveis ​​e legíveis armazenam dados em um buffer interno que pode ser recuperado usando writable. writableState. getBuffer () ou readable. readableState. buffer. respectivamente. A quantidade de dados potencialmente armazenados em buffer depende da opção highWaterMark passada para o construtor de fluxos. Para fluxos normais, a opção highWaterMark especifica um número total de bytes. Para fluxos que operam no modo de objeto, o highWaterMark especifica um número total de objetos. Os dados são armazenados em fluxos Readable quando a implementação chama stream. push (chunk). Se o consumidor do Stream não chama stream. read (). Os dados permanecerão na fila interna até que ele seja consumido. Uma vez que o tamanho total do buffer de leitura interno atinge o limite especificado por highWaterMark. O fluxo interromperá temporariamente a leitura de dados do recurso subjacente até que os dados atualmente armazenados em buffer possam ser consumidos (ou seja, o fluxo irá parar de chamar o método readable. read () interno usado para preencher o buffer de leitura). Os dados são armazenados em buffer em fluxos graváveis ​​quando o método writable. write (chunk) é chamado repetidamente. Enquanto o tamanho total do buffer interno de gravação está abaixo do limite definido pelo highWaterMark. Chamadas para writable. write () retornará true. Uma vez que o tamanho do buffer interno atinge ou excede o highWaterMark. False será retornado. Um objetivo fundamental da API de fluxo e, em particular, o método stream. pipe () é limitar o armazenamento em buffer de dados a níveis aceitáveis, de forma que fontes e destinos de velocidades diferentes não excedam a memória disponível. Como os fluxos Duplex e Transform são legíveis e graváveis, cada um mantém dois buffers internos separados usados ​​para leitura e escrita, permitindo que cada lado opere independentemente do outro, mantendo um fluxo de dados apropriado e eficiente. Por exemplo, as instâncias net. Socket são fluxos Duplex cujo lado Readable permite o consumo de dados recebidos do soquete e cujo lado Writeable permite gravar dados no soquete. Como os dados podem ser gravados no soquete a uma taxa mais rápida ou lenta do que os dados recebidos, é importante que cada lado opere (e buffer) independentemente do outro. API para Stream Consumidores Quase todas as aplicações Node. js, não importa quão simples, use streams de alguma forma. O seguinte é um exemplo de usar fluxos em um aplicativo Node. js que implementa um servidor HTTP: Os fluxos graváveis ​​(como res no exemplo) expõem métodos como write () e end () que são usados ​​para gravar dados no fluxo . Os fluxos legíveis usam a API EventEmitter para notificar o código do aplicativo quando os dados estão disponíveis para serem lidos do fluxo. Esses dados disponíveis podem ser lidos do fluxo de várias maneiras. Ambos os fluxos graváveis ​​e legíveis usam a API EventEmitter de várias maneiras para comunicar o estado atual do fluxo. Aplicativos que estão gravando dados ou consumindo dados de um fluxo não são necessários para implementar as interfaces de fluxo diretamente e, geralmente, não têm motivo para chamar require (39stream39). Os desenvolvedores que desejam implementar novos tipos de fluxos devem consultar a seção API para implementadores de fluxo. Fluxos graváveis ​​Os fluxos graváveis ​​são uma abstração para um destino para o qual os dados são gravados. Exemplos de fluxos graváveis ​​incluem: Nota. Alguns desses exemplos são na verdade fluxos Duplex que implementam a interface Gravável. Todos os fluxos de gravação implementam a interface definida pela classe stream. Writable. Embora instâncias específicas dos fluxos graváveis ​​possam diferir de várias maneiras, todos os fluxos graváveis ​​seguem o mesmo padrão de uso fundamental ilustrado no exemplo abaixo: Classe: stream. Writable Evento: 39close39 O evento 39close39 é emitido quando o fluxo e qualquer um dos recursos subjacentes (Um descritor de arquivo, por exemplo) foram fechados. O evento indica que não mais eventos serão emitidos, e nenhuma computação adicional ocorrerá. Nem todos os fluxos graváveis ​​emitem o evento 39close39. Evento: 39drain39 Se uma chamada para stream. write (chunk) retorna false. O evento 39drain39 será emitido quando for apropriado para retomar a gravação de dados para o fluxo. Evento: 39error39 O evento 39error39 é emitido se ocorrer um erro durante a gravação ou dados de canalização. O callback ouvinte é passado um único argumento de erro quando chamado. Nota . O fluxo não está fechado quando o evento 39error39 é emitido. Evento: 39finish39 O evento 39finish39 é emitido após o método stream. end () ter sido chamado e todos os dados foram liberados para o sistema subjacente. Evento: 39pipe39 O evento 39pipe39 é emitido quando o método stream. pipe () é chamado em um fluxo legível, adicionando este gravável ao seu conjunto de destinos. Evento: 39unpipe39 O evento 39unpipe39 é emitido quando o método stream. unpipe () é chamado em um fluxo Readable, removendo este Writable de seu conjunto de destinos. Writable. cork () O método writable. cork () força todos os dados escritos a serem armazenados em buffer na memória. Os dados armazenados em buffer serão liberados quando os métodos stream. uncork () ou stream. end () forem chamados. A principal intenção de writable. cork () é evitar uma situação em que escrever muitos pequenos pedaços de dados em um fluxo não causa um backup no buffer interno que teria um impacto adverso no desempenho. Em tais situações, as implementações que implementam o método writable. writev () podem executar gravações armazenadas de forma mais otimizada. Writable. end (chunk, codificação, callback) chunk ltStringgt ltBuffergt ltanygt Dados opcionais para gravação. Para fluxos que não operam no modo de objeto, o pedaço deve ser uma Cadeia de caracteres ou um Buffer. Para fluxos de modo de objeto, chunk pode ser qualquer valor JavaScript diferente de null. Codificação ltStringgt A codificação, se chunk for um String callback ltFunctiongt Callback opcional para quando o fluxo é terminado Chamando o método writable. end () sinaliza que não mais dados serão gravados no Writable. O opcional chunk e encoding argumentos permitem que um último pedaço adicional de dados a ser escrito imediatamente antes de fechar o fluxo. Se fornecida, a função de retorno de chamada opcional é anexada como um ouvinte para o evento 39finish39. Chamar o método stream. write () depois de chamar stream. end () irá gerar um erro. Writable. setDefaultEncoding (encoding) Adicionado em: v0.11.15 O método writable. setDefaultEncoding () define a codificação padrão para um fluxo de gravação. Writable. uncork () O método writable. uncork () limpa todos os dados armazenados em buffer desde que o stream. cork () foi chamado. Ao usar writable. cork () e writable. uncork () para gerenciar o armazenamento em buffer de gravações em um fluxo, é recomendável que as chamadas para writable. uncork () sejam diferidas usando process. nextTick (). Isso permite que batching de todas as chamadas writable. write () que ocorrem em uma determinada fase de loop de evento Node. js. Se o método writable. cork () é chamado várias vezes em um fluxo, o mesmo número de chamadas para writable. uncork () deve ser chamado para liberar os dados armazenados em buffer. Chunk ltStringgt ltBuffergt Os dados para gravar a codificação ltStringgt A codificação, se chunk for um String callback ltFunctiongt Chamada de retorno para quando este pedaço de dados é liberado Retorna: ltBooleangt false se o fluxo desejar para o código de chamada Para aguardar que o evento 39drain39 seja emitido antes de continuar a escrever dados adicionais caso contrário verdadeiro. O método writable. write () grava alguns dados no fluxo e chama o retorno de chamada fornecido uma vez que os dados foram totalmente tratados. Se ocorrer um erro, o retorno de chamada pode ou não pode ser chamado com o erro como seu primeiro argumento. Para detectar de forma confiável erros de gravação, adicione um ouvinte para o evento 39error39. O valor de retorno indica se o bloco escrito foi armazenado em buffer internamente eo buffer excedeu o highWaterMark configurado quando o fluxo foi criado. Se false for retornado, outras tentativas de gravar dados no fluxo devem ser pausadas até que o evento 39drain39 seja emitido. Um fluxo gravável no modo de objeto sempre ignorará o argumento de codificação. Fluxos de leitura Os fluxos de leitura são uma abstração para uma fonte a partir da qual os dados são consumidos. Exemplos de streams legíveis incluem: Todos os streams Readable implementam a interface definida pela classe stream. Readable. Dois modos Os fluxos legíveis funcionam de forma eficiente em um dos dois modos: fluindo e pausado. Quando em modo de fluxo, os dados são lidos automaticamente do sistema subjacente e fornecidos a uma aplicação o mais rapidamente possível utilizando eventos através da interface EventEmitter. No modo pausado, o método stream. read () deve ser chamado explicitamente para ler blocos de dados do fluxo. Todos os fluxos Readable começam no modo pausado, mas podem ser alternados para o modo de fluxo de uma das seguintes maneiras: O Readable pode retornar ao modo pausado usando um dos seguintes: Se não houver destinos de pipe, chamando stream. pause () Método. Se houver destinos de pipe, removendo quaisquer manipuladores de eventos 39data39 e removendo todos os destinos de pipe chamando o método stream. unpipe (). O conceito importante a ser lembrado é que um Readable não gerará dados até que um mecanismo para consumir ou ignorar esses dados seja fornecido. Se o mecanismo de consumo estiver desativado ou removido, o Readable tentará parar de gerar os dados. Nota . Por motivos de compatibilidade com versões anteriores, a remoção de manipuladores de eventos 39data39 não interromperá automaticamente o fluxo. Além disso, se houver destinos de canal, em seguida, chamar stream. pause () não garante que o fluxo permanecerá pausado uma vez que esses destinos drenar e pedir mais dados. Nota . Se um Readable é comutado para o modo de fluxo e não há consumidores disponíveis lidar com os dados, esses dados serão perdidos. Isso pode ocorrer, por exemplo, quando o método readable. resume () é chamado sem um ouvinte conectado ao evento 39data39 ou quando um manipulador de eventos 39data39 é removido do fluxo. Três estados Os modos de operação quottwo para um fluxo legível são uma abstração simplificada para o gerenciamento de estado interno mais complicado que está acontecendo dentro da implementação de fluxo legível. Especificamente, em qualquer ponto no tempo, cada Readable está em um dos três estados possíveis: readable. readableState. flowing null readable. readableState. flowing false readable. readableState. flowing true Quando readable. readableState. flowing é null. Nenhum mecanismo para consumir os dados de fluxos é fornecido para que o fluxo não gere seus dados. Anexar um ouvinte para o evento 39data39, chamar o método readable. pipe () ou chamar o método readable. resume () alterará readable. readableState. flowing para true. Fazendo com que o Readable comece a emitir ativamente eventos à medida que os dados são gerados. Chamando readable. pause (). Readable. unpipe (). Ou receber uma pressão de quotback fará com que o readable. readableState. flowing seja definido como falso. Interrompendo temporariamente o fluxo de eventos, mas não interrompendo a geração de dados. Enquanto readable. readableState. flowing é false. Os dados podem estar acumulando dentro do buffer interno dos fluxos. Escolher Uma A API de Fluxo Readable evoluiu em várias versões do Node. js e fornece vários métodos de consumir dados de fluxo. Em geral, os desenvolvedores devem escolher um dos métodos de consumir dados e nunca devem usar vários métodos para consumir dados de um único fluxo. O uso do método readable. pipe () é recomendado para a maioria dos usuários, uma vez que foi implementado para fornecer a maneira mais fácil de consumir dados de fluxo. Os desenvolvedores que exigem controle mais refinado sobre a transferência ea geração de dados podem usar as APIs EventEmitter e readable. pause () / readable. resume (). Classe: stream. Readable Evento: 39close39 O evento 39close39 é emitido quando o fluxo e qualquer um de seus recursos subjacentes (um descritor de arquivo, por exemplo) foram fechados. O evento indica que não mais eventos serão emitidos, e nenhuma computação adicional ocorrerá. Nem todos os fluxos legíveis emitem o evento 39close39. Evento: 39data39 chunk ltBuffergt ltStringgt ltanygt O pedaço de dados. Para fluxos que não estão operando no modo de objeto, o pedaço será uma seqüência de caracteres ou Buffer. Para fluxos que estão no modo de objeto, o pedaço pode ser qualquer valor JavaScript diferente de nulo. O evento 39data39 é emitido sempre que o fluxo está renunciando a propriedade de um pedaço de dados para um consumidor. Isso pode ocorrer sempre que o fluxo é alternado no modo de fluxo chamando readable. pipe (). Readable. resume (). Ou anexando um retorno de chamada do ouvinte ao evento 39data39. O evento 39data39 também será emitido sempre que o método readable. read () é chamado e um pedaço de dados está disponível para ser retornado. Anexar um ouvinte de evento 39data39 a um fluxo que não foi explicitamente pausado irá alternar o fluxo no modo de fluxo. Os dados serão então passados ​​assim que estiverem disponíveis. O retorno de chamada do ouvinte passará o pedaço de dados como uma seqüência se uma codificação padrão tiver sido especificada para o fluxo usando o método readable. setEncoding () caso contrário os dados serão passados ​​como um Buffer. Evento: 39end39 O evento 39end39 é emitido quando não há mais dados a serem consumidos a partir do fluxo. Nota . O evento 39end39 não será emitido a menos que os dados sejam completamente consumidos. Isso pode ser feito trocando o fluxo em modo de fluxo ou chamando stream. read () repetidamente até que todos os dados tenham sido consumidos. Evento: 39error39 O evento 39error39 pode ser emitido por uma implementação legível a qualquer momento. Normalmente, isso pode ocorrer se o fluxo subjacente não é capaz de gerar dados devido a uma falha interna subjacente ou quando uma implementação de fluxo tenta empurrar um pedaço inválido de dados. O callback do ouvinte será passado um único objeto de erro. Evento: 39readable39 O evento 39readable39 é emitido quando há dados disponíveis para serem lidos do fluxo. Em alguns casos, anexar um ouvinte para o evento 39readable39 fará com que alguma quantidade de dados seja lida em um buffer interno. O evento 39readable39 também será emitido uma vez que o fim dos dados do fluxo tenha sido atingido, mas antes do evento 39end39 ser emitido. Efetivamente, o evento 39readable39 indica que o fluxo tem novas informações: novos dados estão disponíveis ou o fim do fluxo foi atingido. No primeiro caso, stream. read () retornará os dados disponíveis. No último caso, stream. read () retornará null. Por exemplo, no exemplo a seguir, foo. txt é um arquivo vazio: A saída de execução desse script é: Nota. Em geral, os mecanismos de eventos readable. pipe () e 39data39 são preferidos ao uso do evento 39readable39. Readable. isPaused () O método readable. isPaused () retorna o estado operacional atual do Readable. Isso é usado principalmente pelo mecanismo que está subjacente ao método readable. pipe (). Na maioria dos casos típicos, não haverá razão para usar este método diretamente. Readable. pause () O método readable. pause () fará com que um fluxo no modo de fluxo pare de emitir eventos 39data39, saindo do modo de fluxo. Quaisquer dados disponíveis ficam no buffer interno. Readable. pipe (destino, opções) destino ltstream. Writablegt O destino para escrever opções de dados ltObjectgt Opções de pipe end ltBooleangt Termina o escritor quando o leitor termina. O padrão é true. O método readable. pipe () atribui um fluxo de gravação ao legível. Fazendo com que ele mude automaticamente para o modo de fluxo e empurre todos os seus dados para o anexo Gravável. O fluxo de dados será gerenciado automaticamente para que o fluxo de gravação de destino não seja superado por um fluxo de leitura mais rápida. O exemplo a seguir canaliza todos os dados do legível para um arquivo chamado file. txt: É possível anexar vários fluxos graváveis ​​a um único fluxo legível. O método readable. pipe () retorna uma referência ao fluxo de destino, tornando possível a criação de cadeias de fluxos canalizados: Por padrão, stream. end () é chamado no fluxo de destino Writable quando o fluxo de fonte Readable emite 39end39. De modo que o destino não é mais gravável. Para desativar esse comportamento padrão, a opção end pode ser passada como false. Fazendo com que o fluxo de destino permaneça aberto, como ilustrado no exemplo a seguir: Uma ressalva importante é que se o fluxo de leitura emite um erro durante o processamento, o destino de gravação não é fechado automaticamente. Se ocorrer um erro, será necessário fechar manualmente cada fluxo para evitar vazamentos de memória. Nota . Process. stderr e process. stdout Os fluxos graváveis ​​nunca são fechados até que o processo Node. js seja encerrado, independentemente das opções especificadas. Readable. read (size) O método readable. read () puxa alguns dados do buffer interno e retorna-os. Se nenhum dado disponível para ser lido, null é retornado. Por padrão, os dados serão retornados como um objeto Buffer, a menos que uma codificação tenha sido especificada usando o método readable. setEncoding () ou o fluxo esteja operando no modo objeto. O argumento tamanho opcional especifica um número específico de bytes para ler. Se os bytes de tamanho não estiverem disponíveis para serem lidos, null será retornado a menos que o fluxo tenha terminado, caso em que todos os dados restantes no buffer interno serão retornados (mesmo se exceder tamanho bytes). Se o argumento size não for especificado, todos os dados contidos no buffer interno serão retornados. O método readable. read () só deve ser chamado em fluxos legíveis operando em modo pausado. No modo de fluxo, readable. read () é chamado automaticamente até que o buffer interno esteja completamente drenado. Em geral, recomenda-se que os desenvolvedores evitem o uso do evento 39readable39 eo método readable. read () em favor de usar readable. pipe () ou o evento 39data39. Um fluxo legível no modo de objeto sempre retornará um único item de uma chamada para readable. read (tamanho). Independentemente do valor do argumento size. Nota: Se o método readable. read () retornar um pedaço de dados, um evento 39data39 também será emitido. Nota . Chamar stream. read (tamanho) após o evento 39end39 ter sido emitido retornará null. Nenhum erro de tempo de execução será gerado. Readable. resume () O método readable. resume () faz com que um fluxo Readable explicitamente pausado retome a emissão de eventos 39data39, mudando o fluxo para o modo de fluxo. O método readable. resume () pode ser usado para consumir completamente os dados de um fluxo sem realmente processar qualquer um desses dados como ilustrado no seguinte exemplo: readable. setEncoding (codificação) O método readable. setEncoding () define a codificação de caracteres padrão Para dados lidos a partir do fluxo Readable. Definir uma codificação faz com que os dados de fluxo sejam retornados como seqüência de caracteres da codificação especificada em vez de objetos Buffer. Por exemplo, chamar readable. setEncoding (39utf839) fará com que os dados de saída sejam interpretados como dados UTF-8 e passados ​​como strings. Chamar readable. setEncoding (39hex39) fará com que os dados sejam codificados em formato de cadeia hexadecimal. O fluxo Readable irá tratar corretamente caracteres de vários bytes entregues através do fluxo que de outra forma ficaria indevidamente descodificado se simplesmente puxado do fluxo como objetos Buffer. A codificação pode ser desativada chamando readable. setEncoding (null). Essa abordagem é útil ao trabalhar com dados binários ou com seqüências de caracteres de vários bytes grandes espalhadas por vários pedaços. Readable. unpipe (destination) O método readable. unpipe () desanega um fluxo de gravação anexado anteriormente usando o método stream. pipe (). Se o destino não for especificado, então todos os tubos são destacados. Se o destino é especificado, mas nenhum pipe é configurado para ele, o método não faz nada. Readable. unshift (chunk) O método readable. unshift () empurra um pedaço de dados de volta para o buffer interno. Isso é útil em determinadas situações em que um fluxo está sendo consumido por um código que precisa de quotun-consumir alguma quantidade de dados que ele tem puxado otimistamente para fora da fonte, de modo que os dados podem ser passados ​​para algum outro partido. Nota . O método stream. unshift (chunk) não pode ser chamado depois que o evento 39end39 foi emitido ou um erro de tempo de execução será lançado. Os desenvolvedores que usam stream. unshift () frequentemente devem considerar mudar para o uso de um fluxo de Transformação em vez disso. Consulte a seção API para implementadores de fluxo para obter mais informações. Nota . Ao contrário de stream. push (pedaço). Stream. unshift (chunk) não vai terminar o processo de leitura, redefinindo o estado de leitura interna do fluxo. Isso pode causar resultados inesperados se readable. unshift () for chamado durante uma leitura (ou seja, a partir de uma implementação stream. read () em um fluxo personalizado). Following the call to readable. unshift() with an immediate stream. push(3939) will reset the reading state appropriately, however it is best to simply avoid calling readable. unshift() while in the process of performing a read. readable. wrap(stream) Versions of Node. js prior to v0.10 had streams that did not implement the entire stream module API as it is currently defined. (See Compatibility for more information.) When using an older Node. js library that emits 39data39 events and has a stream. pause() method that is advisory only, the readable. wrap() method can be used to create a Readable stream that uses the old stream as its data source. It will rarely be necessary to use readable. wrap() but the method has been provided as a convenience for interacting with older Node. js applications and libraries. Duplex and Transform Streams Class: stream. Duplex Duplex streams are streams that implement both the Readable and Writable interfaces. Examples of Duplex streams include: Class: stream. Transform Transform streams are Duplex streams where the output is in some way related to the input. Like all Duplex streams, Transform streams implement both the Readable and Writable interfaces. Examples of Transform streams include: API for Stream Implementers The stream module API has been designed to make it possible to easily implement streams using JavaScript39s prototypical inheritance model. First, a stream developer would declare a new JavaScript class that extends one of the four basic stream classes ( stream. Writable. stream. Readable. stream. Duplex. or stream. Transform ), making sure the call the appropriate parent class constructor: The new stream class must then implement one or more specific methods, depending on the type of stream being created, as detailed in the chart below: Note . The implementation code for a stream should never call the quotpublicquot methods of a stream that are intended for use by consumers (as described in the API for Stream Consumers section). Doing so may lead to adverse side effects in application code consuming the stream. Simplified Construction For many simple cases, it is possible to construct a stream without relying on inheritance. This can be accomplished by directly creating instances of the stream. Writable. stream. Readable. stream. Duplex or stream. Transform objects and passing appropriate methods as constructor options. Implementing a Writable Stream The stream. Writable class is extended to implement a Writable stream. Custom Writable streams must call the new stream. Writable(options) constructor and implement the writable. write() method. The writable. writev() method may also be implemented. Constructor: new stream. Writable(options) options ltObjectgt highWaterMark ltNumbergt Buffer level when stream. write() starts returning false. Defaults to 16384 (16kb), or 16 for objectMode streams. decodeStrings ltBooleangt Whether or not to decode strings into Buffers before passing them to stream. write(). Defaults to true objectMode ltBooleangt Whether or not the stream. write(anyObj) is a valid operation. When set, it becomes possible to write JavaScript values other than string or Buffer if supported by the stream implementation. Defaults to false write ltFunctiongt Implementation for the stream. write() method. writev ltFunctiongt Implementation for the stream. writev() method. Or, when using pre-ES6 style constructors: Or, using the Simplified Constructor approach: writable. write(chunk, encoding, callback) chunk ltBuffergt ltStringgt The chunk to be written. Will always be a buffer unless the decodeStrings option was set to false . encoding ltStringgt If the chunk is a string, then encoding is the character encoding of that string. If chunk is a Buffer. or if the stream is operating in object mode, encoding may be ignored. callback ltFunctiongt Call this function (optionally with an error argument) when processing is complete for the supplied chunk. All Writable stream implementations must provide a writable. write() method to send data to the underlying resource. Note . This function MUST NOT be called by application code directly. It should be implemented by child classes, and called only by the internal Writable class methods only. The callback method must be called to signal either that the write completed successfully or failed with an error. The first argument passed to the callback must be the Error object if the call failed or null if the write succeeded. It is important to note that all calls to writable. write() that occur between the time writable. write() is called and the callback is called will cause the written data to be buffered. Once the callback is invoked, the stream will emit a 39drain39 event. If a stream implementation is capable of processing multiple chunks of data at once, the writable. writev() method should be implemented. If the decodeStrings property is set in the constructor options, then chunk may be a string rather than a Buffer, and encoding will indicate the character encoding of the string. This is to support implementations that have an optimized handling for certain string data encodings. If the decodeStrings property is explicitly set to false. the encoding argument can be safely ignored, and chunk will always be a Buffer . The writable. write() method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs. writable. writev(chunks, callback) chunks ltArraygt The chunks to be written. Each chunk has following format: . callback ltFunctiongt A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks. Note . This function MUST NOT be called by application code directly. It should be implemented by child classes, and called only by the internal Writable class methods only. The writable. writev() method may be implemented in addition to writable. write() in stream implementations that are capable of processing multiple chunks of data at once. If implemented, the method will be called with all chunks of data currently buffered in the write queue. The writable. writev() method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs. Errors While Writing It is recommended that errors occurring during the processing of the writable. write() and writable. writev() methods are reported by invoking the callback and passing the error as the first argument. This will cause an 39error39 event to be emitted by the Writable. Throwing an Error from within writable. write() can result in expected and inconsistent behavior depending on how the stream is being used. Using the callback ensures consistent and predictable handling of errors. An Example Writable Stream The following illustrates a rather simplistic (and somewhat pointless) custom Writable stream implementation. While this specific Writable stream instance is not of any real particular usefulness, the example illustrates each of the required elements of a custom Writable stream instance: Implementing a Readable Stream The stream. Readable class is extended to implement a Readable stream. Custom Readable streams must call the new stream. Readable(options) constructor and implement the readable. read() method. new stream. Readable(options) options ltObjectgt highWaterMark ltNumbergt The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Defaults to 16384 (16kb), or 16 for objectMode streams encoding ltStringgt If specified, then buffers will be decoded to strings using the specified encoding. Defaults to null objectMode ltBooleangt Whether this stream should behave as a stream of objects. Meaning that stream. read(n) returns a single value instead of a Buffer of size n. Defaults to false read ltFunctiongt Implementation for the stream. read() method. Or, when using pre-ES6 style constructors: Or, using the Simplified Constructor approach: readable. read(size) size ltNumbergt Number of bytes to read asynchronously Note . This function MUST NOT be called by application code directly. It should be implemented by child classes, and called only by the internal Readable class methods only. All Readable stream implementations must provide an implementation of the readable. read() method to fetch data from the underlying resource. When readable. read() is called, if data is available from the resource, the implementation should begin pushing that data into the read queue using the this. push(dataChunk) method. read() should continue reading from the resource and pushing data until readable. push() returns false. Only when read() is called again after it has stopped should it resume pushing additional data onto the queue. Note . Once the readable. read() method has been called, it will not be called again until the readable. push() method is called. The size argument is advisory. For implementations where a quotreadquot is a single operation that returns data can use the size argument to determine how much data to fetch. Other implementations may ignore this argument and simply provide data whenever it becomes available. There is no need to quotwaitquot until size bytes are available before calling stream. push(chunk) . The readable. read() method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs. readable. push(chunk, encoding) chunk ltBuffergt ltNullgt ltStringgt Chunk of data to push into the read queue encoding ltStringgt Encoding of String chunks. Must be a valid Buffer encoding, such as 39utf839 or 39ascii39 Returns ltBooleangt true if additional chunks of data may continued to be pushed false otherwise. When chunk is a Buffer or string. the chunk of data will be added to the internal queue for users of the stream to consume. Passing chunk as null signals the end of the stream (EOF), after which no more data can be written. When the Readable is operating in paused mode, the data added with readable. push() can be read out by calling the readable. read() method when the 39readable39 event is emitted. When the Readable is operating in flowing mode, the data added with readable. push() will be delivered by emitting a 39data39 event. The readable. push() method is designed to be as flexible as possible. For example, when wrapping a lower-level source that provides some form of pause/resume mechanism, and a data callback, the low-level source can be wrapped by the custom Readable instance as illustrated in the following example: Note . The readable. push() method is intended be called only by Readable Implementers, and only from within the readable. read() method. Errors While Reading It is recommended that errors occurring during the processing of the readable. read() method are emitted using the 39error39 event rather than being thrown. Throwing an Error from within readable. read() can result in expected and inconsistent behavior depending on whether the stream is operating in flowing or paused mode. Using the 39error39 event ensures consistent and predictable handling of errors. An Example Counting Stream The following is a basic example of a Readable stream that emits the numerals from 1 to 1,000,000 in ascending order, and then ends. Implementing a Duplex Stream A Duplex stream is one that implements both Readable and Writable. such as a TCP socket connection. Because JavaScript does not have support for multiple inheritance, the stream. Duplex class is extended to implement a Duplex stream (as opposed to extending the stream. Readable and stream. Writable classes). Note . The stream. Duplex class prototypically inherits from stream. Readable and parasitically from stream. Writable . Custom Duplex streams must call the new stream. Duplex(options) constructor and implement both the readable. read() and writable. write() methods. new stream. Duplex(options) options ltObjectgt Passed to both Writable and Readable constructors. Also has the following fields: allowHalfOpen ltBooleangt Defaults to true. If set to false. then the stream will automatically end the readable side when the writable side ends and vice versa. readableObjectMode ltBooleangt Defaults to false. Sets objectMode for readable side of the stream. Has no effect if objectMode is true . writableObjectMode ltBooleangt Defaults to false. Sets objectMode for writable side of the stream. Has no effect if objectMode is true . Or, when using pre-ES6 style constructors: Or, using the Simplified Constructor approach: An Example Duplex Stream The following illustrates a simple example of a Duplex stream that wraps a hypothetical lower-level source object to which data can be written, and from which data can be read, albeit using an API that is not compatible with Node. js streams. The following illustrates a simple example of a Duplex stream that buffers incoming written data via the Writable interface that is read back out via the Readable interface. The most important aspect of a Duplex stream is that the Readable and Writable sides operate independently of one another despite co-existing within a single object instance. Object Mode Duplex Streams For Duplex streams, objectMode can be set exclusively for either the Readable or Writable side using the readableObjectMode and writableObjectMode options respectively. In the following example, for instance, a new Transform stream (which is a type of Duplex stream) is created that has an object mode Writable side that accepts JavaScript numbers that are converted to hexadecimal strings on the Readable side. Implementing a Transform Stream A Transform stream is a Duplex stream where the output is computed in some way from the input. Examples include zlib streams or crypto streams that compress, encrypt, or decrypt data. Note . There is no requirement that the output be the same size as the input, the same number of chunks, or arrive at the same time. For example, a Hash stream will only ever have a single chunk of output which is provided when the input is ended. A zlib stream will produce output that is either much smaller or much larger than its input. The stream. Transform class is extended to implement a Transform stream. The stream. Transform class prototypically inherits from stream. Duplex and implements its own versions of the writable. write() and readable. read() methods. Custom Transform implementations must implement the transform. transform() method and may also implement the transform. flush() method. Note . Care must be taken when using Transform streams in that data written to the stream can cause the Writable side of the stream to become paused if the output on the Readable side is not consumed. new stream. Transform(options) Or, when using pre-ES6 style constructors: Or, using the Simplified Constructor approach: Events: 39finish39 and 39end39 The 39finish39 and 39end39 events are from the stream. Writable and stream. Readable classes, respectively. The 39finish39 event is emitted after stream. end() is called and all chunks have been processed by stream. transform(). The 39end39 event is emitted after all data has been output, which occurs after the callback in transform. flush() has been called. transform. flush(callback) callback ltFunctiongt A callback function (optionally with an error argument) to be called when remaining data has been flushed. Note . This function MUST NOT be called by application code directly. It should be implemented by child classes, and called only by the internal Readable class methods only. In some cases, a transform operation may need to emit an additional bit of data at the end of the stream. For example, a zlib compression stream will store an amount of internal state used to optimally compress the output. When the stream ends, however, that additional data needs to be flushed so that the compressed data will be complete. Custom Transform implementations may implement the transform. flush() method. This will be called when there is no more written data to be consumed, but before the 39end39 event is emitted signaling the end of the Readable stream. Within the transform. flush() implementation, the readable. push() method may be called zero or more times, as appropriate. The callback function must be called when the flush operation is complete. The transform. flush() method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs. transform. transform(chunk, encoding, callback) chunk ltBuffergt ltStringgt The chunk to be transformed. Will always be a buffer unless the decodeStrings option was set to false . encoding ltStringgt If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value - 39buffer39, ignore it in this case. callback ltFunctiongt A callback function (optionally with an error argument and data) to be called after the supplied chunk has been processed. Note . This function MUST NOT be called by application code directly. It should be implemented by child classes, and called only by the internal Readable class methods only. All Transform stream implementations must provide a transform() method to accept input and produce output. The transform. transform() implementation handles the bytes being written, computes an output, then passes that output off to the readable portion using the readable. push() method. The transform. push() method may be called zero or more times to generate output from a single input chunk, depending on how much is to be output as a result of the chunk. It is possible that no output is generated from any given chunk of input data. The callback function must be called only when the current chunk is completely consumed. The first argument passed to the callback must be an Error object if an error occurred while processing the input or null otherwise. If a second argument is passed to the callback. it will be forwarded on to the readable. push() method. In other words the following are equivalent: The transform. transform() method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs. Class: stream. PassThrough The stream. PassThrough class is a trivial implementation of a Transform stream that simply passes the input bytes across to the output. Its purpose is primarily for examples and testing, but there are some use cases where stream. PassThrough is useful as a building block for novel sorts of streams. Additional Notes Compatibility with Older Node. js Versions In versions of Node. js prior to v0.10, the Readable stream interface was simpler, but also less powerful and less useful. Rather than waiting for calls the stream. read() method, 39data39 events would begin emitting immediately. Applications that would need to perform some amount of work to decide how to handle data were required to store read data into buffers so the data would not be lost. The stream. pause() method was advisory, rather than guaranteed. This meant that it was still necessary to be prepared to receive 39data39 events even when the stream was in a paused state . In Node. js v0.10, the Readable class was added. For backwards compatibility with older Node. js programs, Readable streams switch into quotflowing modequot when a 39data39 event handler is added, or when the stream. resume() method is called. The effect is that, even when not using the new stream. read() method and 39readable39 event, it is no longer necessary to worry about losing 39data39 chunks. While most applications will continue to function normally, this introduces an edge case in the following conditions: No 39data39 event listener is added. The stream. resume() method is never called. The stream is not piped to any writable destination. For example, consider the following code: In versions of Node. js prior to v0.10, the incoming message data would be simply discarded. However, in Node. js v0.10 and beyond, the socket remains paused forever. The workaround in this situation is to call the stream. resume() method to begin the flow of data: In addition to new Readable streams switching into flowing mode, pre-v0.10 style streams can be wrapped in a Readable class using the readable. wrap() method. readable. read(0) There are some cases where it is necessary to trigger a refresh of the underlying readable stream mechanisms, without actually consuming any data. In such cases, it is possible to call readable. read(0). which will always return null . If the internal read buffer is below the highWaterMark. and the stream is not currently reading, then calling stream. read(0) will trigger a low-level stream. read() call. While most applications will almost never need to do this, there are situations within Node. js where this is done, particularly in the Readable stream class internals. readable. push(3939) Use of readable. push(3939) is not recommended. Pushing a zero-byte string or Buffer to a stream that is not in object mode has an interesting side effect. Because it is a call to readable. push(). the call will end the reading process. However, because the argument is an empty string, no data is added to the readable buffer so there is nothing for a user to consume. Node. js v6.7.0 Documentation Table of Contents Buffer Prior to the introduction of TypedArray in ECMAScript 2015 (ES6), the JavaScript language had no mechanism for reading or manipulating streams of binary data. The Buffer class was introduced as part of the Node. js API to make it possible to interact with octet streams in the context of things like TCP streams and file system operations. Now that TypedArray has been added in ES6, the Buffer class implements the Uint8Array API in a manner that is more optimized and suitable for Node. js39 use cases. Instances of the Buffer class are similar to arrays of integers but correspond to fixed-sized, raw memory allocations outside the V8 heap. The size of the Buffer is established when it is created and cannot be resized. The Buffer class is a global within Node. js, making it unlikely that one would need to ever use require(39buffer39).Buffer . Buffer. from(). Buffer. alloc(). and Buffer. allocUnsafe() In versions of Node. js prior to v6, Buffer instances were created using the Buffer constructor function, which allocates the returned Buffer differently based on what arguments are provided: Passing a number as the first argument to Buffer() (e. g. new Buffer(10) ), allocates a new Buffer object of the specified size. The memory allocated for such Buffer instances is not initialized and can contain sensitive data . Such Buffer instances must be initialized manually by using either buf. fill(0) or by writing to the Buffer completely. While this behavior is intentional to improve performance, development experience has demonstrated that a more explicit distinction is required between creating a fast-but-uninitialized Buffer versus creating a slower-but-safer Buffer . Passing a string, array, or Buffer as the first argument copies the passed object39s data into the Buffer . Passing an ArrayBuffer returns a Buffer that shares allocated memory with the given ArrayBuffer . Because the behavior of new Buffer() changes significantly based on the type of value passed as the first argument, applications that do not properly validate the input arguments passed to new Buffer(). or that fail to appropriately initialize newly allocated Buffer content, can inadvertently introduce security and reliability issues into their code. To make the creation of Buffer instances more reliable and less error prone, the various forms of the new Buffer() constructor have been deprecated and replaced by separate Buffer. from(). Buffer. alloc(). and Buffer. allocUnsafe() methods. Developers should migrate all existing uses of the new Buffer() constructors to one of these new APIs. Buffer. from(array) returns a new Buffer containing a copy of the provided octets. Buffer. from(arrayBuffer, byteOffset , length) returns a new Buffer that shares the same allocated memory as the given ArrayBuffer . Buffer. from(buffer) returns a new Buffer containing a copy of the contents of the given Buffer . Buffer. from(string, encoding) returns a new Buffer containing a copy of the provided string. Buffer. alloc(size, fill, encoding) returns a quotfilledquot Buffer instance of the specified size. This method can be significantly slower than Buffer. allocUnsafe(size) but ensures that newly created Buffer instances never contain old and potentially sensitive data. Buffer. allocUnsafe(size) and Buffer. allocUnsafeSlow(size) each return a new Buffer of the specified size whose content must be initialized using either buf. fill(0) or written to completely. Buffer instances returned by Buffer. allocUnsafe() may be allocated off a shared internal memory pool if size is less than or equal to half Buffer. poolSize. Instances returned by Buffer. allocUnsafeSlow() never use the shared internal memory pool. The --zero-fill-buffers command line option Node. js can be started using the --zero-fill-buffers command line option to force all newly allocated Buffer instances created using either new Buffer(size). Buffer. allocUnsafe(). Buffer. allocUnsafeSlow() or new SlowBuffer(size) to be automatically zero-filled upon creation. Use of this flag changes the default behavior of these methods and can have a significant impact on performance. Use of the --zero-fill-buffers option is recommended only when necessary to enforce that newly allocated Buffer instances cannot contain potentially sensitive data. What makes Buffer. allocUnsafe() and Buffer. allocUnsafeSlow() quotunsafequot When calling Buffer. allocUnsafe() and Buffer. allocUnsafeSlow(). the segment of allocated memory is uninitialized (it is not zeroed-out). While this design makes the allocation of memory quite fast, the allocated segment of memory might contain old data that is potentially sensitive. Using a Buffer created by Buffer. allocUnsafe() without completely overwriting the memory can allow this old data to be leaked when the Buffer memory is read. While there are clear performance advantages to using Buffer. allocUnsafe(). extra care must be taken in order to avoid introducing security vulnerabilities into an application. Buffers and Character Encodings Buffer instances are commonly used to represent sequences of encoded characters such as UTF-8, UCS2, Base64 or even Hex-encoded data. It is possible to convert back and forth between Buffer instances and ordinary JavaScript strings by using an explicit character encoding. The character encodings currently supported by Node. js include: 39ascii39 - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set. 39utf839 - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. 39utf16le39 - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U10000 to U10FFFF) are supported. 39ucs239 - Alias of 39utf16le39 . 39base6439 - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept quotURL and Filename Safe Alphabetquot as specified in RFC4648, Section 5 . 39latin139 - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345. page 63, to be the Latin-1 supplement block and C0/C1 control codes). 39binary39 - Alias for 39latin139 . 39hex39 - Encode each byte as two hexadecimal characters. Note . Today39s browsers follow the WHATWG spec which aliases both 39latin139 and ISO-8859-1 to win-1252. This means that while doing something like http. get(). if the returned charset is one of those listed in the WHATWG spec it39s possible that the server actually returned win-1252-encoded data, and using 39latin139 encoding may incorrectly decode the characters. Buffers and TypedArray Buffer instances are also Uint8Array instances. However, there are subtle incompatibilities with the TypedArray specification in ECMAScript 2015. For example, while ArrayBufferslice() creates a copy of the slice, the implementation of Bufferslice() creates a view over the existing Buffer without copying, making Bufferslice() far more efficient. It is also possible to create new TypedArray instances from a Buffer with the following caveats: The Buffer object39s memory is copied to the TypedArray. not shared. The Buffer object39s memory is interpreted as an array of distinct elements, and not as a byte array of the target type. That is, new Uint32Array(Buffer. from(1, 2, 3, 4)) creates a 4-element Uint32Array with elements 1, 2, 3, 4. not a Uint32Array with a single element 0x1020304 or 0x4030201 . It is possible to create a new Buffer that shares the same allocated memory as a TypedArray instance by using the TypeArray object39s. buffer property. Note that when creating a Buffer using a TypedArray 39s. buffer. it is possible to use only a portion of the underlying ArrayBuffer by passing in byteOffset and length parameters. The Buffer. from() and TypedArray. from() (e. g. Uint8Array. from() ) have different signatures and implementations. Specifically, the TypedArray variants accept a second argument that is a mapping function that is invoked on every element of the typed array: TypedArray. from(source, mapFn, thisArg) The Buffer. from() method, however, does not support the use of a mapping function: Buffers and ES6 iteration Buffer instances can be iterated over using the ECMAScript 2015 (ES6) for..of syntax. Additionally, the buf. values(). buf. keys(). and buf. entries() methods can be used to create iterators. Class: Buffer The Buffer class is a global type for dealing with binary data directly. It can be constructed in a variety of ways. new Buffer(array) Deprecated since: v6.0.0 Allocates a new Buffer using an array of octets. new Buffer(buffer) Deprecated since: v6.0.0 buffer ltBuffergt An existing Buffer to copy data from Copies the passed buffer data onto a new Buffer instance. new Buffer(arrayBuffer, byteOffset , length) Deprecated since: v6.0.0 arrayBuffer ltArrayBuffergt The. buffer property of a TypedArray or ArrayBuffer byteOffset ltIntegergt Where to start copying from arrayBuffer. Default: 0 length ltIntegergt How many bytes to copy from arrayBuffer. Default: arrayBuffer. length - byteOffset When passed a reference to the. buffer property of a TypedArray instance, the newly created Buffer will share the same allocated memory as the TypedArray . The optional byteOffset and length arguments specify a memory range within the arrayBuffer that will be shared by the Buffer . new Buffer(size) Deprecated since: v6.0.0 size ltIntegergt The desired length of the new Buffer Allocates a new Buffer of size bytes. The size must be less than or equal to the value of buffer. kMaxLength. Otherwise, a RangeError is thrown. A zero-length Buffer will be created if size lt 0 . Unlike ArrayBuffers. the underlying memory for Buffer instances created in this way is not initialized . The contents of a newly created Buffer are unknown and could contain sensitive data . Use buf. fill(0) to initialize a Buffer to zeroes. new Buffer(string, encoding) Deprecated since: v6.0.0 Creates a new Buffer containing the given JavaScript string string. If provided, the encoding parameter identifies the character encoding of string . Class Method: Buffer. alloc(size, fill, encoding) size ltIntegergt The desired length of the new Buffer fill ltStringgt ltBuffergt ltIntegergt A value to pre-fill the new Buffer with. Default: 0 encoding ltStringgt If fill is a string, this is its encoding. Default: 39utf839 Allocates a new Buffer of size bytes. If fill is undefined. the Buffer will be zero-filled . The size must be less than or equal to the value of buffer. kMaxLength. Otherwise, a RangeError is thrown. A zero-length Buffer will be created if size lt 0 . If fill is specified, the allocated Buffer will be initialized by calling buf. fill(fill) . If both fill and encoding are specified, the allocated Buffer will be initialized by calling buf. fill(fill, encoding) . Calling Buffer. alloc() can be significantly slower than the alternative Buffer. allocUnsafe() but ensures that the newly created Buffer instance contents will never contain sensitive data . A TypeError will be thrown if size is not a number. Class Method: Buffer. allocUnsafe(size) size ltIntegergt The desired length of the new Buffer Allocates a new non-zero-filled Buffer of size bytes. The size must be less than or equal to the value of buffer. kMaxLength. Otherwise, a RangeError is thrown. A zero-length Buffer will be created if size lt 0 . The underlying memory for Buffer instances created in this way is not initialized . The contents of the newly created Buffer are unknown and may contain sensitive data . Use buf. fill(0) to initialize such Buffer instances to zeroes. A TypeError will be thrown if size is not a number. Note that the Buffer module pre-allocates an internal Buffer instance of size Buffer. poolSize that is used as a pool for the fast allocation of new Buffer instances created using Buffer. allocUnsafe() (and the deprecated new Buffer(size) constructor) only when size is less than or equal to Buffer. poolSize gtgt 1 (floor of Buffer. poolSize divided by two). Use of this pre-allocated internal memory pool is a key difference between calling Buffer. alloc(size, fill) vs. Buffer. allocUnsafe(size).fill(fill). Specifically, Buffer. alloc(size, fill) will never use the internal Buffer pool, while Buffer. allocUnsafe(size).fill(fill) will use the internal Buffer pool if size is less than or equal to half Buffer. poolSize. The difference is subtle but can be important when an application requires the additional performance that Buffer. allocUnsafe() provides. Class Method: Buffer. allocUnsafeSlow(size) size ltIntegergt The desired length of the new Buffer Allocates a new non-zero-filled and non-pooled Buffer of size bytes. The size must be less than or equal to the value of buffer. kMaxLength. Otherwise, a RangeError is thrown. A zero-length Buffer will be created if size lt 0 . The underlying memory for Buffer instances created in this way is not initialized . The contents of the newly created Buffer are unknown and may contain sensitive data . Use buf. fill(0) to initialize such Buffer instances to zeroes. When using Buffer. allocUnsafe() to allocate new Buffer instances, allocations under 4KB are, by default, sliced from a single pre-allocated Buffer. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffer instances. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many Persistent objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using Buffer. allocUnsafeSlow() then copy out the relevant bits. Use of Buffer. allocUnsafeSlow() should be used only as a last resort after a developer has observed undue memory retention in their applications. A TypeError will be thrown if size is not a number. Class Method: Buffer. byteLength(string, encoding) string ltStringgt ltBuffergt ltTypedArraygt ltDataViewgt ltArrayBuffergt A value to calculate the length of encoding ltStringgt If string is a string, this is its encoding. Default: 39utf839 Return: ltIntegergt The number of bytes contained within string Returns the actual byte length of a string. This is not the same as String. prototype. length since that returns the number of characters in a string. When string is a Buffer / DataView / TypedArray / ArrayBuffer. the actual byte length is returned. Otherwise, converts to String and returns the byte length of string. Class Method: Bufferpare(buf1, buf2) Added in: v0.11.13 Compares buf1 to buf2 typically for the purpose of sorting arrays of Buffer instances. This is equivalent to calling buf1pare(buf2) . Class Method: Buffer. concat(list, totalLength) list ltArraygt List of Buffer instances to concat totalLength ltIntegergt Total length of the Buffer instances in list when concatenated Return: ltBuffergt Returns a new Buffer which is the result of concatenating all the Buffer instances in the list together. If the list has no items, or if the totalLength is 0, then a new zero-length Buffer is returned. If totalLength is not provided, it is calculated from the Buffer instances in list. This however causes an additional loop to be executed in order to calculate the totalLength. so it is faster to provide the length explicitly if it is already known. Example: Create a single Buffer from a list of three Buffer instances Class Method: Buffer. from(array) Allocates a new Buffer using an array of octets. A TypeError will be thrown if array is not an Array . Class Method: Buffer. from(arrayBuffer, byteOffset, length) arrayBuffer ltArrayBuffergt The. buffer property of a TypedArray or ArrayBuffer byteOffset ltIntegergt Where to start copying from arrayBuffer. Default: 0 length ltIntegergt How many bytes to copy from arrayBuffer. Default: arrayBuffer. length - byteOffset When passed a reference to the. buffer property of a TypedArray instance, the newly created Buffer will share the same allocated memory as the TypedArray . The optional byteOffset and length arguments specify a memory range within the arrayBuffer that will be shared by the Buffer . A TypeError will be thrown if arrayBuffer is not an ArrayBuffer . Class Method: Buffer. from(buffer) buffer ltBuffergt An existing Buffer to copy data from Copies the passed buffer data onto a new Buffer instance. A TypeError will be thrown if buffer is not a Buffer . Class Method: Buffer. from(string, encoding) Creates a new Buffer containing the given JavaScript string string. If provided, the encoding parameter identifies the character encoding of string . A TypeError will be thrown if str is not a string. Class Method: Buffer. isBuffer(obj) Added in: v0.1.101 Returns true if obj is a Buffer. false otherwise. Class Method: Buffer. isEncoding(encoding) Returns true if encoding contains a supported character encoding, or false otherwise. Class Property: Buffer. poolSize This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. bufindex The index operator index can be used to get and set the octet at position index in buf. The values refer to individual bytes, so the legal value range is between 0x00 and 0xFF (hex) or 0 and 255 (decimal). Example: Copy an ASCII string into a Buffer. one byte at a time bufpare(target, targetStart, targetEnd, sourceStart, sourceEnd) Added in: v0.11.13 target ltBuffergt A Buffer to compare to targetStart ltIntegergt The offset within target at which to begin comparison. Default: 0 targetEnd ltIntegergt The offset with target at which to end comparison (not inclusive). Ignored when targetStart is undefined. Default: target. length sourceStart ltIntegergt The offset within buf at which to begin comparison. Ignored when targetStart is undefined. Default: 0 sourceEnd ltIntegergt The offset within buf at which to end comparison (not inclusive). Ignored when targetStart is undefined. Default: buf. length Return: ltIntegergt Compares buf with target and returns a number indicating whether buf comes before, after, or is the same as target in sort order. Comparison is based on the actual sequence of bytes in each Buffer . 0 is returned if target is the same as buf 1 is returned if target should come before buf when sorted. -1 is returned if target should come after buf when sorted. The optional targetStart. targetEnd. sourceStart. and sourceEnd arguments can be used to limit the comparison to specific ranges within target and buf respectively. A RangeError will be thrown if: targetStart lt 0. sourceStart lt 0. targetEnd gt target. byteLength or sourceEnd gt source. byteLength . buf. copy(target, targetStart, sourceStart, sourceEnd) target ltBuffergt A Buffer to copy into. targetStart ltIntegergt The offset within target at which to begin copying to. Default: 0 sourceStart ltIntegergt The offset within buf at which to begin copying from. Ignored when targetStart is undefined. Default: 0 sourceEnd ltIntegergt The offset within buf at which to stop copying (not inclusive). Ignored when sourceStart is undefined. Default: buf. length Return: ltIntegergt The number of bytes copied. Copies data from a region of buf to a region in target even if the target memory region overlaps with buf . Example: Create two Buffer instances, buf1 and buf2. and copy buf1 from byte 16 through byte 19 into buf2. starting at the 8th byte in buf2 Example: Create a single Buffer and copy data from one region to an overlapping region within the same Buffer buf. entries() Creates and returns an iterator of index, byte pairs from the contents of buf . Example: Log the entire contents of a Buffer buf. equals(otherBuffer) Added in: v0.11.13 Returns true if both buf and otherBuffer have exactly the same bytes, false otherwise. buf. fill(value, offset, end, encoding) value ltStringgt ltBuffergt ltIntegergt The value to fill buf with offset ltIntegergt Where to start filling buf. Default: 0 end ltIntegergt Where to stop filling buf (not inclusive). Default: buf. length encoding ltStringgt If value is a string, this is its encoding. Default: 39utf839 Return: ltBuffergt A reference to buf Fills buf with the specified value. If the offset and end are not given, the entire buf will be filled. This is meant to be a small simplification to allow the creation and filling of a Buffer to be done on a single line. Example: Fill a Buffer with the ASCII character 39h39 value is coerced to a uint32 value if it is not a String or Integer. If the final write of a fill() operation falls on a multi-byte character, then only the first bytes of that character that fit into buf are written. Example: Fill a Buffer with a two-byte character buf. indexOf(value, byteOffset, encoding) value ltStringgt ltBuffergt ltIntegergt What to search for byteOffset ltIntegergt Where to begin searching in buf. Default: 0 encoding ltStringgt If value is a string, this is its encoding. Default: 39utf839 Return: ltIntegergt The index of the first occurrence of value in buf or -1 if buf does not contain value a string, value is interpreted according to the character encoding in encoding . a Buffer. value will be used in its entirety. To compare a partial Buffer use buf. slice() . a number, value will be interpreted as an unsigned 8-bit integer value between 0 and 255 . buf. includes(value, byteOffset, encoding) value ltStringgt ltBuffergt ltIntegergt What to search for byteOffset ltIntegergt Where to begin searching in buf. Default: 0 encoding ltStringgt If value is a string, this is its encoding. Default: 39utf839 Return: ltBooleangt true if value was found in buf. false otherwise buf. keys() Creates and returns an iterator of buf keys (indices). buf. lastIndexOf(value, byteOffset, encoding) value ltStringgt ltBuffergt ltIntegergt What to search for byteOffset ltIntegergt Where to begin searching in buf (not inclusive). Default: buf. length encoding ltStringgt If value is a string, this is its encoding. Default: 39utf839 Return: ltIntegergt The index of the last occurrence of value in buf or -1 if buf does not contain value Identical to buf. indexOf(). except buf is searched from back to front instead of front to back. buf. length Returns the amount of memory allocated for buf in bytes. Note that this does not necessarily reflect the amount of quotusablequot data within buf . Example: Create a Buffer and write a shorter ASCII string to it While the length property is not immutable, changing the value of length can result in undefined and inconsistent behavior. Applications that wish to modify the length of a Buffer should therefore treat length as read-only and use buf. slice() to create a new Buffer . buf. readDoubleBE(offset, noAssert) buf. readDoubleLE(offset, noAssert) Added in: v0.11.15 offset ltIntegergt Where to start reading. Must satisfy: 0 lt offset lt buf. length - 8 noAssert ltBooleangt Skip offset validation Default: false Return: ltNumbergt Reads a 64-bit double from buf at the specified offset with specified endian format ( readDoubleBE() returns big endian, readDoubleLE() returns little endian). Setting noAssert to true allows offset to be beyond the end of buf. but the result should be considered undefined behavior. buf. readFloatBE(offset, noAssert) buf. readFloatLE(offset, noAssert) Added in: v0.11.15 offset ltIntegergt Where to start reading. Must satisfy: 0 lt offset lt buf. length - 4 noAssert ltBooleangt Skip offset validation Default: false Return: ltNumbergt Reads a 32-bit float from buf at the specified offset with specified endian format ( readFloatBE() returns big endian, readFloatLE() returns little endian). Setting noAssert to true allows offset to be beyond the end of buf. but the result should be considered undefined behavior. buf. readInt8(offset, noAssert) offset ltIntegergt Where to start reading. Must satisfy: 0 lt offset lt buf. length - 1 noAssert ltBooleangt Skip offset validation Default: false Return: ltIntegergt Reads a signed 8-bit integer from buf at the specified offset . Setting noAssert to true allows offset to be beyond the end of buf. but the result should be considered undefined behavior. Integers read from a Buffer are interpreted as two39s complement signed values. buf. readInt16BE(offset, noAssert) buf. readInt16LE(offset, noAssert) offset ltIntegergt Where to start reading. Must satisfy: 0 lt offset lt buf. length - 2 noAssert ltBooleangt Skip offset validation Default: false Return: ltIntegergt Reads a signed 16-bit integer from buf at the specified offset with the specified endian format ( readInt16BE() returns big endian, readInt16LE() returns little endian). Setting noAssert to true allows offset to be beyond the end of buf. but the result should be considered undefined behavior. Integers read from a Buffer are interpreted as two39s complement signed values. buf. readInt32BE(offset, noAssert) buf. readInt32LE(offset, noAssert) offset ltIntegergt Where to start reading. Must satisfy: 0 lt offset lt buf. length - 4 noAssert ltBooleangt Skip offset validation Default: false Return: ltIntegergt Reads a signed 32-bit integer from buf at the specified offset with the specified endian format ( readInt32BE() returns big endian, readInt32LE() returns little endian). Setting noAssert to true allows offset to be beyond the end of buf. but the result should be considered undefined behavior. Integers read from a Buffer are interpreted as two39s complement signed values. buf. readIntBE(offset, byteLength, noAssert) buf. readIntLE(offset, byteLength, noAssert) Added in: v0.11.15 offset ltIntegergt Where to start reading. Must satisfy: 0 lt offset lt buf. length - byteLength byteLength ltIntegergt How many bytes to read. Must satisfy: 0 lt byteLength lt 6 noAssert ltBooleangt Skip offset and byteLength validation Default: false Return: ltIntegergt Reads byteLength number of bytes from buf at the specified offset and interprets the result as a two39s complement signed value. Supports up to 48 bits of accuracy. Setting noAssert to true allows offset to be beyond the end of buf. but the result should be considered undefined behavior. buf. readUInt8(offset, noAssert) offset ltIntegergt Where to start reading. Must satisfy: 0 lt offset lt buf. length - 1 noAssert ltBooleangt Skip offset validation Default: false Return: ltIntegergt Reads an unsigned 8-bit integer from buf at the specified offset . Setting noAssert to true allows offset to be beyond the end of buf. but the result should be considered undefined behavior. buf. readUInt16BE(offset, noAssert) buf. readUInt16LE(offset, noAssert) offset ltIntegergt Where to start reading. Must satisfy: 0 lt offset lt buf. length - 2 noAssert ltBooleangt Skip offset validation Default: false Return: ltIntegergt Reads an unsigned 16-bit integer from buf at the specified offset with specified endian format ( readUInt16BE() returns big endian, readUInt16LE() returns little endian). Setting noAssert to true allows offset to be beyond the end of buf. but the result should be considered undefined behavior. buf. readUInt32BE(offset, noAssert) buf. readUInt32LE(offset, noAssert) offset ltIntegergt Where to start reading. Must satisfy: 0 lt offset lt buf. length - 4 noAssert ltBooleangt Skip offset validation Default: false Return: ltIntegergt Reads an unsigned 32-bit integer from buf at the specified offset with specified endian format ( readUInt32BE() returns big endian, readUInt32LE() returns little endian). Setting noAssert to true allows offset to be beyond the end of buf. but the result should be considered undefined behavior. buf. readUIntBE(offset, byteLength, noAssert) buf. readUIntLE(offset, byteLength, noAssert) Added in: v0.11.15 offset ltIntegergt Where to start reading. Must satisfy: 0 lt offset lt buf. length - byteLength byteLength ltIntegergt How many bytes to read. Must satisfy: 0 lt byteLength lt 6 noAssert ltBooleangt Skip offset and byteLength validation Default: false Return: ltIntegergt Reads byteLength number of bytes from buf at the specified offset and interprets the result as an unsigned integer. Supports up to 48 bits of accuracy. Setting noAssert to true allows offset to be beyond the end of buf. but the result should be considered undefined behavior. buf. slice(start, end) start ltIntegergt Where the new Buffer will start. Default: 0 end ltIntegergt Where the new Buffer will end (not inclusive). Default: buf. length Return: ltBuffergt Returns a new Buffer that references the same memory as the original, but offset and cropped by the start and end indices. Note that modifying the new Buffer slice will modify the memory in the original Buffer because the allocated memory of the two objects overlap. Example: Create a Buffer with the ASCII alphabet, take a slice, and then modify one byte from the original Buffer Specifying negative indexes causes the slice to be generated relative to the end of buf rather than the beginning. buf. swap16() Interprets buf as an array of unsigned 16-bit integers and swaps the byte-order in-place . Throws a RangeError if buf. length is not a multiple of 2. buf. swap32() Interprets buf as an array of unsigned 32-bit integers and swaps the byte-order in-place . Throws a RangeError if buf. length is not a multiple of 4. buf. swap64() Interprets buf as an array of 64-bit numbers and swaps the byte-order in-place . Throws a RangeError if buf. length is not a multiple of 8. Note that JavaScript cannot encode 64-bit integers. This method is intended for working with 64-bit floats. buf. toString(encoding, start, end) encoding ltStringgt The character encoding to decode to. Default: 39utf839 start ltIntegergt Where to start decoding. Default: 0 end ltIntegergt Where to stop decoding (not inclusive). Default: buf. length Return: ltStringgt Decodes buf to a string according to the specified character encoding in encoding. start and end may be passed to decode only a subset of buf . buf. toJSON() Returns a JSON representation of buf. JSON. stringify() implicitly calls this function when stringifying a Buffer instance. buf. values() Creates and returns an iterator for buf values (bytes). This function is called automatically when a Buffer is used in a for..of statement. buf. write(string, offset, length, encoding) string ltStringgt String to be written to buf offset ltIntegergt Where to start writing string. Default: 0 length ltIntegergt How many bytes to write. Default: buf. length - offset encoding ltStringgt The character encoding of string. Default: 39utf839 Return: ltIntegergt Number of bytes written Writes string to buf at offset according to the character encoding in encoding. The length parameter is the number of bytes to write. If buf did not contain enough space to fit the entire string, only a partial amount of string will be written. However, partially encoded characters will not be written. buf. writeDoubleBE(value, offset, noAssert) buf. writeDoubleLE(value, offset, noAssert) Added in: v0.11.15 value ltNumbergt Number to be written to buf offset ltIntegergt Where to start writing. Must satisfy: 0 lt offset lt buf. length - 8 noAssert ltBooleangt Skip value and offset validation Default: false Return: ltIntegergt offset plus the number of bytes written Writes value to buf at the specified offset with specified endian format ( writeDoubleBE() writes big endian, writeDoubleLE() writes little endian). value should be a valid 64-bit double. Behavior is undefined when value is anything other than a 64-bit double. Setting noAssert to true allows the encoded form of value to extend beyond the end of buf. but the result should be considered undefined behavior. buf. writeFloatBE(value, offset, noAssert) buf. writeFloatLE(value, offset, noAssert) Added in: v0.11.15 value ltNumbergt Number to be written to buf offset ltIntegergt Where to start writing. Must satisfy: 0 lt offset lt buf. length - 4 noAssert ltBooleangt Skip value and offset validation Default: false Return: ltIntegergt offset plus the number of bytes written Writes value to buf at the specified offset with specified endian format ( writeFloatBE() writes big endian, writeFloatLE() writes little endian). value should be a valid 32-bit float. Behavior is undefined when value is anything other than a 32-bit float. Setting noAssert to true allows the encoded form of value to extend beyond the end of buf. but the result should be considered undefined behavior. buf. writeInt8(value, offset, noAssert) value ltIntegergt Number to be written to buf offset ltIntegergt Where to start writing. Must satisfy: 0 lt offset lt buf. length - 1 noAssert ltBooleangt Skip value and offset validation Default: false Return: ltIntegergt offset plus the number of bytes written Writes value to buf at the specified offset. value should be a valid signed 8-bit integer. Behavior is undefined when value is anything other than a signed 8-bit integer. Setting noAssert to true allows the encoded form of value to extend beyond the end of buf. but the result should be considered undefined behavior. value is interpreted and written as a two39s complement signed integer. buf. writeInt16BE(value, offset, noAssert) buf. writeInt16LE(value, offset, noAssert) value ltIntegergt Number to be written to buf offset ltIntegergt Where to start writing. Must satisfy: 0 lt offset lt buf. length - 2 noAssert ltBooleangt Skip value and offset validation Default: false Return: ltIntegergt offset plus the number of bytes written Writes value to buf at the specified offset with specified endian format ( writeInt16BE() writes big endian, writeInt16LE() writes little endian). value should be a valid signed 16-bit integer. Behavior is undefined when value is anything other than a signed 16-bit integer. Setting noAssert to true allows the encoded form of value to extend beyond the end of buf. but the result should be considered undefined behavior. value is interpreted and written as a two39s complement signed integer. buf. writeInt32BE(value, offset, noAssert) buf. writeInt32LE(value, offset, noAssert) value ltIntegergt Number to be written to buf offset ltIntegergt Where to start writing. Must satisfy: 0 lt offset lt buf. length - 4 noAssert ltBooleangt Skip value and offset validation Default: false Return: ltIntegergt offset plus the number of bytes written Writes value to buf at the specified offset with specified endian format ( writeInt32BE() writes big endian, writeInt32LE() writes little endian). value should be a valid signed 32-bit integer. Behavior is undefined when value is anything other than a signed 32-bit integer. Setting noAssert to true allows the encoded form of value to extend beyond the end of buf. but the result should be considered undefined behavior. value is interpreted and written as a two39s complement signed integer. buf. writeIntBE(value, offset, byteLength, noAssert) buf. writeIntLE(value, offset, byteLength, noAssert) Added in: v0.11.15 value ltIntegergt Number to be written to buf offset ltIntegergt Where to start writing. Must satisfy: 0 lt offset lt buf. length - byteLength byteLength ltIntegergt How many bytes to write. Must satisfy: 0 lt byteLength lt 6 noAssert ltBooleangt Skip value. offset. and byteLength validation Default: false Return: ltIntegergt offset plus the number of bytes written Writes byteLength bytes of value to buf at the specified offset. Supports up to 48 bits of accuracy. Behavior is undefined when value is anything other than a signed integer. Setting noAssert to true allows the encoded form of value to extend beyond the end of buf. but the result should be considered undefined behavior. buf. writeUInt8(value, offset, noAssert) value ltIntegergt Number to be written to buf offset ltIntegergt Where to start writing. Must satisfy: 0 lt offset lt buf. length - 1 noAssert ltBooleangt Skip value and offset validation Default: false Return: ltIntegergt offset plus the number of bytes written Writes value to buf at the specified offset. value should be a valid unsigned 8-bit integer. Behavior is undefined when value is anything other than an unsigned 8-bit integer. Setting noAssert to true allows the encoded form of value to extend beyond the end of buf. but the result should be considered undefined behavior. buf. writeUInt16BE(value, offset, noAssert) buf. writeUInt16LE(value, offset, noAssert) value ltIntegergt Number to be written to buf offset ltIntegergt Where to start writing. Must satisfy: 0 lt offset lt buf. length - 2 noAssert ltBooleangt Skip value and offset validation Default: false Return: ltIntegergt offset plus the number of bytes written Writes value to buf at the specified offset with specified endian format ( writeUInt16BE() writes big endian, writeUInt16LE() writes little endian). value should be a valid unsigned 16-bit integer. Behavior is undefined when value is anything other than an unsigned 16-bit integer. Setting noAssert to true allows the encoded form of value to extend beyond the end of buf. but the result should be considered undefined behavior. buf. writeUInt32BE(value, offset, noAssert) buf. writeUInt32LE(value, offset, noAssert) value ltIntegergt Number to be written to buf offset ltIntegergt Where to start writing. Must satisfy: 0 lt offset lt buf. length - 4 noAssert ltBooleangt Skip value and offset validation Default: false Return: ltIntegergt offset plus the number of bytes written Writes value to buf at the specified offset with specified endian format ( writeUInt32BE() writes big endian, writeUInt32LE() writes little endian). value should be a valid unsigned 32-bit integer. Behavior is undefined when value is anything other than an unsigned 32-bit integer. Setting noAssert to true allows the encoded form of value to extend beyond the end of buf. but the result should be considered undefined behavior. buf. writeUIntBE(value, offset, byteLength, noAssert) buf. writeUIntLE(value, offset, byteLength, noAssert) value ltIntegergt Number to be written to buf offset ltIntegergt Where to start writing. Must satisfy: 0 lt offset lt buf. length - byteLength byteLength ltIntegergt How many bytes to write. Must satisfy: 0 lt byteLength lt 6 noAssert ltBooleangt Skip value. offset. and byteLength validation Default: false Return: ltIntegergt offset plus the number of bytes written Writes byteLength bytes of value to buf at the specified offset. Supports up to 48 bits of accuracy. Behavior is undefined when value is anything other than an unsigned integer. Setting noAssert to true allows the encoded form of value to extend beyond the end of buf. but the result should be considered undefined behavior. buffer. INSPECTMAXBYTES Returns the maximum number of bytes that will be returned when buf. inspect() is called. This can be overridden by user modules. See util. inspect() for more details on buf. inspect() behavior. Note that this is a property on the buffer module as returned by require(39buffer39). not on the Buffer global or a Buffer instance. buffer. kMaxLength ltIntegergt The largest size allowed for a single Buffer instance On 32-bit architectures, this value is (230)-1 ( 1GB). On 64-bit architectures, this value is (231)-1 ( Class: SlowBuffer Deprecated since: v6.0.0 Returns an un-pooled Buffer . In order to avoid the garbage collection overhead of creating many individually allocated Buffer instances, by default allocations under 4KB are sliced from a single larger allocated object. This approach improves both performance and memory usage since v8 does not need to track and cleanup as many Persistent objects. In the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using SlowBuffer then copy out the relevant bits. Use of SlowBuffer should be used only as a last resort after a developer has observed undue memory retention in their applications. new SlowBuffer(size) Deprecated since: v6.0.0 size ltIntegergt The desired length of the new SlowBuffer Allocates a new SlowBuffer of size bytes. The size must be less than or equal to the value of buffer. kMaxLength. Otherwise, a RangeError is thrown. A zero-length Buffer will be created if size lt 0 . The underlying memory for SlowBuffer instances is not initialized . The contents of a newly created SlowBuffer are unknown and could contain sensitive data. Use buf. fill(0) to initialize a SlowBuffer to zeroes.

No comments:

Post a Comment