javascript - 从公共目录中的 js 文件访问函数
问题描述
我在一个名为 的文件夹中有一个 JS 文件public
,其中也有我的 CSS 文件。我正在尝试从 JS 文件 ( scripts.js
) 访问一个函数,但没有运气。我已经关注了这篇文章(除其他外),但我仍然收到一个错误Error: Cannot find module './scripts.js'
。如果有人可以帮助我,那就太好了。
应用程序.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var request = require("request");
var scripts = require("/scripts.js");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));
const apiUrl = "https://api.darksky.net/forecast/";
const apiKey = "XXX";
app.get('/', function(req, res){
res.render("index");
});
app.post('/results', function(req, res){
var lat = req.body.latitude;
var long = req.body.longitude;
request(apiUrl + apiKey + "/" + long + "," + lat, function(error, response, body){
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
var temperature = scripts.converter(data.currently.temperature)
res.render("results", {data: data, temperature: temperature})
} else {
console.log(response.body);
}
});
});
app.get('/results', function(req, res){
res.render("results");
});
app.listen(3000, function(){
console.log("Server has started");
})
脚本.js
module.converter = function(cel) {
var cel = (far - 32) * (5/9);
return cel;
}
exports.data = module;
解决方案
您的模块路径错误。试试var scripts = require("./public/scripts.js");
吧。
您正在加载/scripts.js
,这是一个scripts.js
位于您计算机根目录的文件。要在当前目录中加载文件,您可以执行./scripts.js
. 在当前目录上方的目录中,它将是../scripts.js
.
如果该文件位于当前目录下方的目录中,例如您的情况,它将是“./directoryname/scripts.js”。directoryname
在public
你的情况下
推荐阅读
- java - 通过泛型类获取具有私有构造函数的静态类实例
- php - PHP - 在同一个 try-catch 中包装一个变量块
- java - Collections.reverseOrder() 函数有什么作用?
- python - 在保留小数点的同时在python中四舍五入
- php - PHP 原生 XML 解析器
- powershell - 从 Jenkins 卸载应用程序
- javascript - Javascript 保留单选按钮值、下拉值和复选框选择值
- c# - SpecFlow 步骤类异步初始化
- python - pymodbus解码错误:[输入/输出]没有收到来自远程单元的响应/无法解码响应
- r - Rvest 网页抓取错误 - 识别 css 或 xpath?