2016-12-14 135 views
0

NodeJS Web應用程序是否可以在不使用任何中間件模塊的情況下「導入」並使用本地Javascipt文件的功能?將本地JavaScript文件導入到NodeJS中

編輯:

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的相對路徑是:./cont/cont.js

+0

我想你在談論有一個網頁調用節點javascript函數?如果是這樣的話,那麼不,網頁應用程序正在服務器上運行,瀏覽器中唯一與客戶端JavaScript代碼的通信是通過調用Web服務器。 –

回答

0

是的,你可以只需要('相對文件名')並使用代碼,但你的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