I have a node.js server to create a web chat application. But I have a problem. In one file, I want to get a function from another file with the require
method and module.export
. In my first file (server.js, which is in the root path), the require
method works, but in the /js folder (which is not in the root), it does not work. I installed npm and all packages globally.
Code in chat.js:
const {verifUserConnected, getUserInfo} = require('express');
console.log(verifUserConnected)
Code in connect.js :
function verifUserConnected(){
return isConnected;
}
function getUserInfo(){
return null;
}
module.exports = {
verifUserConnected,
getUserInfo
};
In "Server.js" The require
method works
CodePudding user response:
You've put connect.js in underneath a folder named "public" which implies you are serving it to the browser and trying to run it client-side.
Browsers do not have native support for CommonJS modules (i.e. module.exports
and require
).
Your starting options are:
- Rewrite the client-side code to not use modules
- Rewrite the client-side code to use JavaScript modules (i.e. using
import
,export
and<script type="module"
). - Transpile the modules for use on the browser (e.g. using a tool like Webpack or Parcel.js
However … chat.js attempts to require('express')
. Express will not run in the browser and doesn't export anything named verifUserConnected
either. You'll need to address that too.
CodePudding user response:
In Common JS (Node JS works by default eith Common JS)
const startServer = () => {
// Code
};
module.exports = { startServer }
//Or
exports.startServer = startServer;
To import.
const { startServer } = require("./path");
If you have any question ask me