code
code

Reputation: 6319

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.

[EDIT]

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

Upvotes: 2

Views: 1385

Answers (2)

code
code

Reputation: 6319

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.

Upvotes: 1

sonEtLumiere
sonEtLumiere

Reputation: 4562

As you can see in your error: 'ReferenceError: express is not defined', you need to require express to invoke the static method, try this:

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

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

Upvotes: 4

Related Questions