[英]Import Local Javascript Files into NodeJS
NodeJS Web應用程序是否可以在不使用任何中間件模塊的情況下“導入”並使用本地Javascipt文件的功能?
編輯:
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
是的,您只需要(“相對文件名”)並使用代碼,但是您的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);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.