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
Your problem is solved if you remove the following line:
__dirname
has already been declared in theglobal
namespace.More information you can see in documentation
Server.js lies here
You might be looking for something like this
If you use __dirname You Get
__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
Tested on Node version v12.17.0
Here How I did it