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