skip to Main Content

Hi I am trying to create a static folder in my server.js for image upload but when I declare the const __dirname = path.resolve() the error message

"const __dirname = path.resolve()
^

SyntaxError: Identifier ‘__dirname’ has already been declared"

get thrown

require('dotenv').config()
const path = require('path')
const express = require('express')
const server = express()
const { notFound, errorHandler } = require('./middleware/errorMiddleware')
const { connectDB } = require('./config/db')

const productRoutes = require('./routes/productRoutes.routes')
const userRoutes = require('./routes/userRoutes.routes')
const orderRoutes = require('./routes/orderRoutes.routes')
const uploadRoutes = require('./routes//uploadRoutes.routes')
connectDB()

server.use(express.json())

server.get('/', (req, res) => {
  res.send('API is running.........')
})
//Routes
server.use('/api/products', productRoutes)
server.use('/api/users', userRoutes)
server.use('/api/orders', orderRoutes)
server.use('/api/upload', uploadRoutes)

server.get('/api/config/paypal', (req, res) =>
  res.send(process.env.PAYPAL_CLIENT_ID)
)

const __dirname = path.resolve()
server.use('/uploads', express.static(path.join(__dirname, '/uploads')))

applicationCache.server.use(notFound)
server.use(errorHandler)

//Listen
const PORT = process.env.PORT || 8080
server.listen(
  PORT,
  console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)

Anyone please help thanks !

2

Answers


  1. Your problem is solved if you remove the following line:

    const __dirname = path.resolve()
    

    __dirname has already been declared in the global namespace.

    More information you can see in documentation

    Login or Signup to reply.
  2. Server.js lies here

    App/backend/server.js

    You might be looking for something like this

    App/upload

    If you use __dirname You Get

    App/backend/upload

    __dirname in a node script returns the path of the folder where the current JavaScript file resides.

    If we rename __dirname to __variableOfChoice. We get

        const __variableOfChoice = path.resolve()
        server.use('/uploads', express.static(path.join(__variableOfChoice , 
        '/uploads')))
    

    App/upload

    I was running This command from ./App "start": "node backend/server",

    Tested on Node version v12.17.0
    Here How I did it

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search