2016-12-14 7 views
0

NodeJS Webアプリケーションはミドルウェアモジュールを使用せずにローカルJavasciptファイルの機能を「インポート」して使用できますか?ローカルJavascriptファイルをNodeJSにインポート

EDIT:

cont.js

function getStyles(res,reqFile){ 
    var options={ 
       root:__dirname+'/Views/styles/', 
       headers:{ 
        'Content-Type':'text/css' 
       } 
      }; 

       res.sendFile(reqFile,options,function(err){ 
        if(err){ 
         console.log(err); 
         res.status(err.status).end(); 
        } 
        else { 
         console.log("Sent "+ reqFile); 
        } 
       });  
} 

server.js

var fs = require('fs') 
var path = require('path') 
var express = require('express') 
var app = express(); 
var url = require('url') 
var views="/Views/" 

app.get(/\/Views\/styles\//,function(req,res){ 
var reqPath = url.parse(req.url).pathname; 
var reqFile = path.basename(reqPath); // the requested file 
console.log("VIEWS/STYLES : " + reqPath); 

fs.readdir(__dirname+views+'/styles','utf8',function(err,data){ 
    console.log(data); 
    if(data.includes(reqFile)){ 
     console.log(reqFile+ " Found in data array"); 
      //call function here 
      getStyles(res,reqFile); 
      } 

}); 

server.jsへの相対パスである:

+0

は、私はあなたがノード内のJavaScript関数を呼び出すWebページを持って話をしていると思いますか?そうであれば、Webアプリケーションはサーバー上で実行されており、ブラウザのクライアントJavaScriptコードとの唯一の通信はWebサーバーへの呼び出しによるものです。 –

答えて

0

./cont/cont.jsはい(「相対ファイル名」)を要求してコードを使用することはできますが、cont.cont.jsファイルにはエクスポートを追加する必要があります

のような何か:

cont.js

function getStyles(res,reqFile){ 
    var options={ 
       root:__dirname+'/Views/styles/', 
       headers:{ 
        'Content-Type':'text/css' 
       } 
      }; 

       res.sendFile(reqFile,options,function(err){ 
        if(err){ 
         console.log(err); 
         res.status(err.status).end(); 
        } 
        else { 
         console.log("Sent "+ reqFile); 
        } 
       });  
} 

module.exports = getStyles; 

server.js

var fs = require('fs') 
var path = require('path') 
var express = require('express') 
var app = express(); 
var url = require('url') 
var views="/Views/" 

var getStyles = require('./cont/cont.js') 

app.get(/\/Views\/styles\//,function(req,res){ 
var reqPath = url.parse(req.url).pathname; 
var reqFile = path.basename(reqPath); // the requested file 
console.log("VIEWS/STYLES : " + reqPath); 

fs.readdir(__dirname+views+'/styles','utf8',function(err,data){ 
    console.log(data); 
    if(data.includes(reqFile)){ 
     console.log(reqFile+ " Found in data array"); 
      //call function here 
      getStyles(res,reqFile); 
      } 

}); 
+0

ありがとうstujo、私は投稿を編集しました – SunDontShine

+0

Webリクエストに応じて、サーバにスタイルファイルをブラウザに返す(サービスする)ようにしようとしていますか? – stujo

+0

私はあなたが今しようとしていることを理解していると思う、編集された答えをチェックしてください – stujo

関連する問題