Search code examples
javascripthtmlnode.jsimportnode-modules

Import to script.js from outside public folder


I want to import a variable from my nodejs index.js file, which is in the root directory, into my script.js file, which is in the public folder (from what I understand, the nodejs index file shouldn't be in the public folder). The index.js file is as so:

const { readFile, readFileSync } = require("fs");
const express = require("express");

const app = express();
app.use(express.static("public"));

const txt = readFileSync("./public/articles/1/title.txt", "utf-8");


app.get("/", (request, response) => {
    readFile("./public/html/index.html", "utf-8", (err, html) => {response.send(html);});
});


app.listen(process.env.PORT || 3000, () => console.log(`Live at http://localhost:3000`))

module.exports = { txt };

And I then want to import the txt variable into my script.js file located in ./public/js/script.js:

import txt from "../index.js";
console.log(txt);

However, it still tries to get it from public/index.js, at which point it throws a 404 (I'm new to nodejs). Any way to get the variable from index.js, or should I move it into the public folder?


Solution

  • You were correct not to put index.js in your /public directory.

    For this solution you will need to install a package called ejs

    npm install ejs
    

    After installing create a directory called /views and move your public/html/index.html inside it, and rename it to index.ejs (Don't worry you don't need to move your javascript files)

    Also modify your main server file index.js to this

    const { readFile, readFileSync } = require("fs");
    const express = require("express");
    const app = express();
    
    app.set('view engine', 'ejs');
    app.use(express.static("public"));
    
    
    app.get("/", (req, res) => {
        const txt = readFileSync("./public/articles/1/title.txt", "utf-8");
    
        res.render("index", { txt }) // render the main file
    });
    
    
    app.listen(process.env.PORT || 3000, () => console.log(`Live at http://localhost:3000`))
    

    You can read more here on how ejs works.

    Afterwards open your index.ejs file and find the line where you import the script.js file and modify it to this.

    <script src="script.js" data-text="<%= txt %>"></script>
    

    The data-text will provide the Javascript file whatever was inside your title.txt file. If you need the text file data displayed inside the page you could just add <%= txt %> anywhere inside the .ejs file.

    Lastly to read the data-text value you need to add these lines inside your script.js

    document.addEventListener('DOMContentLoaded', function() {
        var scriptElements = document.querySelectorAll('script[data-text]');
        var txt = scriptElements[scriptElements.length - 1].getAttribute('data-text');
    
        console.log(txt);
    });
    

    If this solved your problem check this answer as correct!