[Fixed] Cant access other files in Node.js


NOTE: There are the same questions on Stack Overflow, but this is NOT a duplicate. Please read carefully.

I’m just getting started with Socket.io on Node, and in my HTML file, I couldn’t acess other files, such as pictures. I’ve seen answers for this on Stack Overflow, but none of them helped me.

I am serving an HTML file to the client, where my HTML file is located in /client/display/index.html

Here’s what I tried: app.use(express.static(path.join(__dirname, 'public')));
And variations of that (including folder names instead of public), and I required path in the top of my file, and I get this error:

ReferenceError: express is not defined
    at /home/runner/Buzzer/index.js:6:9
    at Script.runInContext (vm.js:130:18)
    at Object.<anonymous> (/run_dir/interp.js:209:20)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
    at internal/main/run_main_module.js:17:47

I already installed everythin I needed. Here’s what I added that gave it an error:

const path = require('path');
app.use(express.static(path.join(__dirname, '/')));

And here are some other top stuff in my node file:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

Would really appreciate this if someone could help me.


Seems like if I put anything inside a folder, the js file can’t find it.


Okay, I realized that ('express')() is different from ('express').

I added:

var express = require('express');

const path = require('path');
app.use(express.static(path.join(__dirname, '/')));

And that solved my problem.

Leave a Reply

(*) Required, Your email will not be published