我的程式遇到了一些問題,所以我開始學習如何使用 node.js 除錯器。我有以下內容index.js:
import app from "./server.js" // imports root
import mongodb from "mongodb" // helps conect to mongodb
import dotenv from "dotenv" // helps configure environment variables automatically
import DailyDAO from "./dao/dailyDAO.js" // DAO file contains CRUD material
// configures dotenv
dotenv.config() // New breakpoint here
const MongoClient = mongodb.MongoClient
// This is the port where our local server will listen to the MongoDB Atlas server
const port = process.env.PORT || 8000
const url = process.env.SOLAR_DB_URI
// Connects local VSC server to the MongoDB Atlas server
MongoClient.connect(
url,
{
maxPoolSize: 50,
waitQueueTimeoutMS: 2500
}
)
.catch(err => { // If there is an error, this is executed
console.error(err.stack)
process.exit(1)
})
.then(async client => {
await DailyDAO.injectDB(client)
app.listen(port, () => {
console.log('Connected to: ' url)
console.log('listening on port: ' port)
})
})
當通過沒有斷點的除錯器運行它時,我收到錯誤:
TypeError:無法讀取未定義的屬性(讀取“startsWith”)
當我停在斷點處時,我可以看到它port并且url都未定義。當我正常運行程式時,兩個變數都有預期值。
這些變數在單獨的檔案中定義.env。所以我假設通過除錯器運行這個檔案時,它沒有.env正確訪問。為什么除錯器會這樣做,以及如何在除錯器index.js中訪問值.env?
編輯:這就是我的.env檔案的樣子
SOLAR_DB_URI=mongodb srv://admin:[email protected]/daily_production?retryWrites=true&w=majority
PORT=5000
SOLAR_NS=daily_production
編輯:我正在使用內置于 VSC 中的 node.js 除錯器。要啟動除錯器,我選擇所需的檔案并index.js從我的資源管理器中選擇 run 和 e(在本例中),然后選擇“Run and Debug”按鈕。
編輯:好的,所以我在dotenv.config(). 事實證明,這個函式錯誤地決議了我的 cwd 的路徑。
編輯:好吧,里面dotenv.config()看起來像這樣:
function config(options) {
// Irrelevant code
let dotenvPath = path.resolve(process.cwd(), '.env'); // There is a problem here
// Irrelevant code
}
index.js和所在的目錄.env是%PATH%\solarmonitor\backend\,但是當我運行除錯器時,它決議為只是%PATH%\solarmonitor\。
launch.json編輯:根據@Bergi 的要求,這些是我的除錯器配置:
{
/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\backend\\index.js"
}
]
}
uj5u.com熱心網友回復:
您基本上已經弄清楚了問題所在 - 您的程式是在錯誤的作業目錄中啟動的。VS Code 基本上node backend\index.js在您的作業區檔案夾中運行,這是任何啟動配置的默認作業目錄。
cwd您可以使用啟動配置屬性更改此設定:
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"cwd": "${workspaceFolder}\\backend",
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
"program": "${workspaceFolder}\\backend\\index.js"
}
對于您的特定問題,您還可以配置 VS Code 以從您的.env檔案中提供環境變數,在這種情況下您不需要dotenv.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/511955.html
