将本地Javascript文件导入NodeJS

时间:2016-12-14 03:59:04

标签: javascript node.js

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的相对路径是:./ contt / cont.js

1 个答案:

答案 0 :(得分: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);
           }  

});