2017-01-23 7 views
0

このコードをmodule.exportsにインポートするにはどうすればよいですか?ノードjsエラーのインポート

私はノードjsとjsでかなり新しいです。 は、私はそれをエクスポートすることができますどのように

cache = (duration) => { 
    return (req, res, next) => { 
    let key = '__express__' + req.originalUrl || req.url 
    let cachedBody = mcache.get(key) 
    if (cachedBody) { 
     res.send(cachedBody) 
     return 
    } else { 
     res.sendResponse = res.send 
     res.send = (body) => { 
     mcache.put(key, body, duration * 1000); 
     res.sendResponse(body) 
     } 
     next() 
    } 
    } 
} 

このコードは他のルートで使用することができることをしたいですか?

私のようなものだった:私はしてみてください。また

module.exports = cache = (duration) => { 
     return (req, res, next) => { 
     let key = '__express__' + req.originalUrl || req.url 
     let cachedBody = mcache.get(key) 
     if (cachedBody) { 
      res.send(cachedBody) 
      return 
     } else { 
      res.sendResponse = res.send 
      res.send = (body) => { 
      mcache.put(key, body, duration * 1000); 
      res.sendResponse(body) 
      } 
      next() 
     } 
     } 
    } 

module.export = { 
    cache: function(duration) { 
    return (req, res, next) => { 
    let key = '__express__' + req.originalUrl || req.url 
    let cachedBody = mcache.get(key) 
    if (cachedBody) { 
     res.send(cachedBody) 
     return 
    } else { 
     res.sendResponse = res.send 
     res.send = (body) => { 
     mcache.put(key, body, duration * 1000); 
     res.sendResponse(body) 
     } 
     next() 
    } 
    } 
} 
} 

しかし、私はGETリクエストでそれを使用しよう:

var expCache = require('../../middleware/cache'); 
    router.get('/:sid/fe',expCache.cache(3000),function(req,res) { 

それがもたらす:

TypeError: expCache.cache is not a function 

よろしくあなたはexpCache.cacheを呼び出すことができるように期待している場合は、オブジェクトをエクスポートする必要が

+2

* forループwith git *?申し訳ありません、ここでgitは何ですか? –

答えて

1

module.exports = { 
    cache: // your function 
} 

をしかし、あなたはそれがあるとしてエクスポートモジュールを維持したい場合は、単に電話をその代わりに、このような:

// inside middleware/cache: 
// module.exports = cache = (duration) => { 

var expCache = require('../../middleware/cache'); 

// you can call it as just a function 
router.get('/:sid/fe', expCache(3000), function(req,res) { 
+0

私はこれを理解しています。しかし、それは=文字の中に何かをマークしています:SyntaxError:予期せぬトークン=> – arnoldssss

+0

mah mistake thanks – arnoldssss

1

var expCache = require('../../middleware/cache'); 
router.get('/:sid/fe',expCache(3000),function(req,res) {.. 
をお試しください

あなたのキャッシュ機能は、それを含むオブジェクトではなく、すでにエクスポートしています(ルーターでの使用方法です)。

+0

私はそれを試みましたが、仕事をしません...それはファイルを通過しません – arnoldssss