javascript - How to execute method just one time for application -


i have nodejs application , want execute method file validations just 1 time (this method validate files under node application).

is there elegant way this? events?

the nodejs documentation on modules states that:

modules cached after first time loaded.

which can take advantage of adding static code module. regardless of how many times module loaded, static code retain state(/value).

you can use state method implement method can called whenever -- @ best time during initialization -- ever called once. pretty simple:

var called = false;  function checkfiles() {   if (called) return;    // perform validation   called = true; }  module.exports = {   checkfiles: checkfiles }; 

because of module caching, can require file in many places need , still execute once.

to invoke function, have few options:

for simple application, can call function main module (or function) , invoked @ time. if validation should asynchronous, can wrap main method in function , pass validator callback.

//#! /bin/env node var express = require('express'); var validator = require('./validator');  validator.checkfiles(); var app = express();  var server = app.listen(3000, function () {   ... }); 

for more complicated application, should call function during existing initialization routine (again, using callbacks necessary).

if have nice modern promise-based initializer, add validator first step of chain.


Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -