问题描述
大家好,
首先,感谢您一直是一个如此出色的社区。你们真的在学习和改进我的编程和开发方面帮助了我很多!
我有一个与 Node.js 中的 module.exports 相关的小问题。下面的函数在直接调用时运行没有问题:
const fs = require('fs')
const {nanoid} = require('nanoid')
const createStormDB = () => {
return new Promise((resolve,reject) => {
try{
const id = nanoid(4)
const date = new Date() // Create date string for file naming
let dateString = `${date.toISOString().split('T')[0]}` // Create date string for file naming
let fileName = `${dateString}_deals_${id}.stormdb` // Create date string for file naming
fs.openSync(`../StormDB/${fileName}`,'w')
resolve(fileName)
}catch(err){
reject(err)
}
})
}
module.exports = createStormDB
它在特定文件夹中创建一个具有特定名称的文件。但是当我使用 module.exports = createStormDB
时,我遇到了以下错误:
(node:12516) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory,open '../StormDB/2021-07-19_deals_gYmJ.stormdb'
at Object.openSync (fs.js:476:3)
at C:\Node\Pipedrive-Connector\PipeDriveRequest\scripts\createStormDBFile.js:11:16
at new Promise (<anonymous>)
at createStormDB (C:\Node\Pipedrive-Connector\PipeDriveRequest\scripts\createStormDBFile.js:5:12)
at Object.<anonymous> (C:\Node\Pipedrive-Connector\PipeDriveRequest\play.js:7:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
在导出模块时,我有什么误解吗?我正在使用 require
选项导入此模块!非常感谢您的帮助!
解决方法
函数中的 ..
相对路径是相对于调用脚本当前工作目录的,而不是文件所在的目录。
根据您的路径设置和描述假设数据库位于:C:\Node\Pipedrive-Connector\PipeDriveRequest\StormDB
如果您希望数据库路径保持相对于包含该函数的 javascript 文件,请使用 __dirname
const path = require('path')
const db_path = path.join(__dirname,'..','StormDB',filename)
fs.openSync(db_path,'w')