Node.js Code I have in index.js
let express = require('express')
const path = require('path');
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";
const firebaseConfig = {
...
};
const firebaseApp = initializeApp(firebaseConfig);
const database = getDatabase(firebaseApp);
let app = express()
const port = 8080
app.get('/updateRelay/:relayId/:status', function (req, res) {
const relayId = req.params["relayId"]
const status = req.params["status"]
console.log(relayId,status)
let updateObject = {}
updateObject[relayId] = status
database.ref("iot-device-001/status").set(updateObject, function(error) {
if (error) {
// The write failed...
console.log("Failed with error: " + error)
} else {
// The write was successful...
console.log("success")
}
})
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, '/index.html'));
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
I cannot for the love of God figure out what is wrong with this code. I have tried every documentation and tutorial available and end up with some unexplainable error. Its either this or its Module Not Found. Here is the link for the tutorial I followed which gave me Module Not Found error
Here is the error I have right now
import { initializeApp } from 'firebase/app';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
It seems that your function is not defined as being a module so you can't use import
inside of it. You'll have to use require
You might solve your issue by replacing
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database"
by
var initializeApp = require('firebase/app')
var getDatabase = require('firebase/database')
You will find more explanation here : https://flexiple.com/javascript-require-vs-import/