Node JS Configuration Node JS Configuration express express

Node JS Configuration


Check your directory structure is correct and that you have given the correct permission for Node.js to enter the directories and read the file.

If your directory structure looks like this:

/public    /stylesheets        home.csshome.htmlserver.js

And your server.js code looks like this:

var express = require("express");var app     = express();var path    = require("path");app.get('/',function(req,res) {    res.sendFile(__dirname + '/home.html');})app.use(express.static(__dirname + '/public'));app.listen('3000', function() {     console.log("Listening on port 3000"); });

When you run this:

node ./server.js

And visit this URL in your browser:

http://localhost:3000/stylesheets/home.css

You will get your home.css file returned.


In express js project to configuration database

/config  /database.js/server.js/.envconst http = require('http');const app = require('express')();require('./config/database.js');const bodyParser = require('body-parser');const server = http.createServer(app);server.listen(process.env.ServerPort, '0.0.0.0', () => {  logger.info(`Express server listening on port ${process.env.ServerPort}`);});

When you run this:

node server.js

database.js file

const My = require('jm-ez-mysql');// Init DB Connectionconst connection = My.init({  host: process.env.DBHOST,  user: process.env.DBUSER,  password: process.env.DBPASSWORD,  database: process.env.DATABASE,  dateStrings: true,  charset: 'utf8mb4',  timezone: 'utc',  multipleStatements: true,  connectTimeout: 100 * 60 * 1000,  acquireTimeout: 100 * 60 * 1000,  timeout: 100 * 60 * 1000,});module.exports = {  connection,};


In express js project, as require you can place you static file.

app.use('/static', express.static('public'))Now, you can load the files that are in the public directory from the /static path prefix.http://localhost:3000/static/images/kitten.jpghttp://localhost:3000/static/css/style.csshttp://localhost:3000/static/js/app.jshttp://localhost:3000/static/images/bg.pnghttp://localhost:3000/static/hello.html

https://expressjs.com/en/starter/static-files.htmlcheck this link for how you can connect your static files with express js