const express = require('express');
const upload = require("express-fileupload");
const editJsonFile = require("edit-json-file");
const fs = require('fs');
const app = express();
app.use(upload())
app.use(express.urlencoded({ extended: true }))
const playlist = editJsonFile(`${__dirname}/playlist.json`);
app.post("/upload", (req, res) => {
//Save file from the html form to ./mp3
var file = req.files.file;
req.pipe(fs.createWriteStream("./mp3/" file.name));
res.send("File uploaded");
playlist.append("playlist", file.name)
playlist.save()
}),
app.get("/playlist", (req, res) => {
console.log(playlist.get("playlist"))
let playlist = playlist.get("playlist")
let html = "";
for (let i = 0; i < playlist.length; i ) {
html = `<br>${playlist[i]}`;
}
res.send(html);
}),
Hey, Im trying to make a music player, but somehow I get the error:
ReferenceError: Cannot access 'playlist' before initialization
at C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\index.js:20:17
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:284:15
at Function.process_params (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:346:12)
at next (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\index.js:280:10)
at urlencodedParser (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\body-parser\lib\types\urlencoded.js:91:7)
at Layer.handle [as handle_request] (C:\Users\Jakob\Documents\Bots\API\PiMusicPlayerV2\node_modules\express\lib\router\layer.js:95:5)
I can write to the Database without any issues, but when I try to read from it I get the error above, what can I do?
CodePudding user response:
app.get("/playlist", (req, res) => {
console.log(playlist.get("playlist"))
let playlist = playlist.get("playlist")
The second line console.log(playlist.get("playlist"))
is trying to print the playlist variable but its declared in the next line, hence no access to that particular variable ergo the error. You can only access something after it has been initialized.
CodePudding user response:
I think you are overwriting the playlist variable. The file is playlist and when you get the element you assign it to playlist as well
Also, a file is not a database