npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@smn-official/node.helpers

v5.0.1

Published

Ferramentas para uso diverso

Downloads

4

Readme

NODE HELPERS

Version v5.0.0

Node >= v.10

 > npm i @smn-official/node.helpers
helpers = require('@smn-official/node.helpers');

#----------------------------------------------------------------------

CLUSTER


const Cluster = new helpers.Cluster({
    cpus: 2, // Quantidade de processadores 
    isProduction: false, //Variavel indicar com aplicação estiver em produção
    maxTentativas: 4, // Maximo de tentativas para subir a aplicação
    clusterError: (worker)=>{}; // função executada caso acabe as tentativas de subir a aplicação
});

Cluster.init();     //Iniciar a aplicação
Cluster.started();  //Se iniciar com sucesso

#----------------------------------------------------------------------

CRYPT


const Crypt = new helpers.crypt.Blowfish('key');

Crypt.encrypt(value);
Crypt.decrypt(value);

#----------------------------------------------------------------------

SETTINGS

Config

  • Objeto para parâmetros da aplicação

const Settings = new helpers.Settings({
    //atributos
});
//Acessar os parâmetros
Settings.?;

Métodos


//Merge Settings.config com objetos passados
Settings.$assign({},...);

//Retorna true ou false para valor passado
Settings.$idObject({});

//Merge Settings.config com config local caso nâo produção
Settings.$devSettings('./config/environment/localSettings.js');

// Retorna -> porta setada em Settings.port OU Settings.api.nomeApi.port
Settings.$port 

// Retorna -> host setado em Settings.host OU Settings.api.nomeApi.host
Settings.$host 

// Retorna -> $host + $port + '/'
Settings.$url 

#----------------------------------------------------------------------

DATE

RETURN STRING

helpers.Date.short      // 00/00/0000
helpers.Date.shortTime  // 00/00/0000 24:00:00
helpers.Date.long       // November 19th 2017, 20:46:06
helpers.Date.dayWeek    // Domingo

RETURN DATE

helpers.Date.now        // new Date()

MÉTODOS


helpers.Date.dateDiff(new Date(2000, 2, 1));                                // 17 'anos'
helpers.Date.dateDiff(new Date(2000, 2, 1), 'm');                           // 231 'meses'
helpers.Date.dateDiff(new Date(2000, 2, 1), new Date(2005, 2, 1));          // 5 'anos'
helpers.Date.dateDiff(new Date(2000, 2, 1), new Date(2005, 2, 1), 'd');     // 1826 dias
//--
helpers.Date.addDay(dias, date);        // Quantidade de dias = 1, date = new Date()
helpers.Date.addMonth(meses, date);     // Quantidade de meses = 1, date = new Date()
helpers.Date.addYear(anos, date);       // Quantidade de anos = 1, date = new Date()

#----------------------------------------------------------------------

FORMAT

MÉTODOS


helpers.Format.money(value, currency)                   //  R$ 0,00
helpers.Format.cpfCnpj(value)                           //  000.000.000-00 OR 00.000.000/0000-00
helpers.Format.rg(value)                                //  00.000.000-0
helpers.Format.telefone(numero, ddd, parentese)         //  00 00000-0000 OR (00) 0000-0000            
helpers.Format.cep(value)                               //  00000-000
helpers.Format.porcentagem(value)                       //  0% , 0,00% 
helpers.Format.date(date, format /* Opcional */)        //  Default - dd/MM/yyyy
 

EMAIL

Config


email = helpers.email({
    host : "host",
    port : 587,
    auth : {
        user : "user email",
        pass : "password",
        name: 'nome'
    },
    logger : false,
    secure : false
});

USE


const Email = email({
    from: '', // Opcional --> default config.auth.user
    to: '',
    subject: '',
    text: '',
    html: ''
});

await Email
    .attachment('logo.png', './src/resources', 'logo')              // Add cid
    .attachment('doc.txt', 'src/resources')                         // Add anexo
    .attachment('data:text/plain;base64,aGVw12sbGda8gd29dswybGQ=')  // Add Base64
    .send();

#----------------------------------------------------------------------

EXCEL

Config


const Excel = new helpers.Excel({
    headers: ['Nome', 'E-mail', 'Telefone', 'Celular'],
    rowsName: ['nome', 'email', 'telefone', 'celular'],
    rows: {
        "nome": "Thiago Moreira",
        "email": "[email protected]",
        "telefone": "(47) 3565-4587",
        "celular": "(47) 99231-2600",
    },
    root: './caminho',
    fileName: 'excel.xlsx',
    planName: 'sheet1' /* Opcional */,
    widthCols: [30, 40, 20, null, 15, 15, 15, 15]
});

USE


await Excel.build(); //Gerar excel

#----------------------------------------------------------------------

FILE

Config

const File = new helpers.File('filename.txt', '/src/resources');

Métodos


File.upload(file);
File.remove();
File.get(encoding /* Opcional */);
File.base64ToFile(base64); // Convert base64 para file
File.uploadImgBase64(imagem, extensao /* Opcional -> override extensão do base64 */);
File.base64Prepare(base64); // Prepara o base64 para a conversão.

Path


File._fullPath; // Retorna caminho completo com filename
File._path; // Retorna caminho diretório

#----------------------------------------------------------------------

CORS

  • MIDDLEWARE *

SET

  • Set function finish no 'res'
  • Recebe objeto contendo statusCode para informar status da resposta
app.use(helpers.cors())

/*
    res.finish = (response, noNext) => {
        res.status(response.statusCode).json(response);
        if (!noNext) next();
    };
*/

Override FINISH

  • Set função excutada dentro do cors
app.use(helpers.cors((req,res,next)=>{
    res.finish = (response, noNext) => {
        res.status(response.statusCode).json(response);
        if (!noNext) next();
    };
}));

#----------------------------------------------------------------------

RESPONSE

Config

Response = new helpers.Response();

Métodos

let Error = new Response.Error(message, content, status /* Opcional default = 500 */);
let Success = new Response.Ok(content, status /* Opcional default = 200 */);
let Scope = new Response.Scope(content, status /* Opcional default = 400 */);

Scope

let Scope = new Response.Scope(content, status /* Opcional default = 400 */);

Scope.validate(object)
    .field('atributo')
    .isNotEmpty()
    .isNotNull()
    .length(max, min /* OPCIONAL */)
    .isEmail()
    .isInt()
    .isNumber()
    .maxValue(value)
    .minValue(value)
    .equals(compare, message)
    .isCpf()
    .isCnpj()
    .end();

Scope.isSuccess // true OR false.
Scope.get // return objeto error {messages,statusCode,content,isSuccess}

Scope.end() // True OR False throw exception passando Scope.get
Scope.addMessage(campo, error, value);
Scope.addContent(content);

// Scope Mensagem retorno format

messages = {
    nome: { 
        required: true
    },
    email: {
        maxLength: true
    }
}

Padrão StatusCode Api Return

SCOPE
    * 400 -	dados inválidos.
SUCCESS
    * 200 - Ok	
    * 204 - Usuario/dados nao encontrado 
ERROR
    * 401 - inválido(nao autorizado).
    * 402 - usuario expirado
    * 404 - Erros de rota - caminha não encontrados.
    * 409 - Conflito

    * 502 - Erro na comunicação com api.
    * 502/500 - Erro na comunicação com banco de dados.(conexao/execucao)
    * 500 - Erro ao executar metodos/funcionalidades.	 

#----------------------------------------------------------------------

EXCEPTION


helpers.exception('message', 500 /* STATUS OPCIONAL - default 500 */, {} /* CONTENT OPCIONAL*/)
// throw interno.

#----------------------------------------------------------------------

MIDDLEWARE

Error


const errors = helpers.middleware.error;

// Tratar requisição não finalizada     -  next()
app.use(errors.notfound);
// Tratar requisição passando parâmetro -  next('error')
app.use(errors.serverError);

Response


// Gerar funções para finalizar requisição
app.use(helpers.middleware.response);

res.ok(content, status /* DEFAULT 200 */);
res.error(message, content, status /* DEFAULT 500 */);
res.finish(response);
res.default(status, content);

#----------------------------------------------------------------------