0

I have a JS file in a folder called public, which also has my CSS file in it. I'm trying to access a function from the JS file (scripts.js), but am having no luck. I've followed this post (amongst others), but I am still getting an error of Error: Cannot find module './scripts.js'. If anyone can help me out, that would be great.

app.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");
})

scripts.js

module.converter = function(cel) {
        var cel = (far - 32) * (5/9);
        return cel;
}

exports.data = module;
  • 1
    `require` doesn't access the files like a browser would (where `/scripts.js` would be the website root), but rather like your file explorer does. The right path is likely `./public/scripts.js`. – Luca Kiebel Feb 21 '19 at 19:54

1 Answers1

0

The path to your module is wrong. Try var scripts = require("./public/scripts.js"); instead.

You are loading /scripts.js, which is a scripts.js file located at your computers root. To load a file in the current directory, you would do ./scripts.js. In a directory above the current one, it would be ../scripts.js.

If the file is in a directory below the current directory, like in your case, it would be './directoryname/scripts.js'. directoryname being public in your case

Aravind Voggu
  • 1,491
  • 12
  • 17