0

今天是个好日子,

首先,感谢您一直是这样一个了不起的社区。你们真的在学习和改进我的编程和开发方面帮助了我很多!

我有一个与 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选项导入此模块!非常感谢你的帮忙!

4

1 回答 1

0

函数中的..相对路径是相对于调用脚本当前工作目录的,而不是文件所在的目录。

假设根据您的路径设置和描述,数据库位于: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')
于 2021-07-19T23:12:33.367 回答