I'm creating an npm package called ctgen and I need to reference a folder within that package. Should I hard code the reference to that folder?
e.g. src = './node_modules/ctgen/scaffold'
or is there a pre-made function that will do this for me?
For a bit more clarity on my issue. I have the following function in my package:
var createFile = function (fileName, componentName, doc) {
// Tell the user what is happening
console.log(chalk.blue('\nCreating', fileName, '...'))
// Bring in the scaffold files (note this should point to the scaffold folder in node modules/ctgen)
var scaffold = './scaffold/' + fileName
fs.readFile(scaffold, 'utf8', function (err, data) {
if (err) return console.log(chalk.red(err))
var result = data.replace(/%cname%/g, componentName)
if (doc) {
var d = new Date()
result = result.replace(/%cfname%/g, doc.componentName)
result = result.replace(/%cdesc%/g, doc.componentDesc)
result = result.replace(/%cauthor%/g, doc.userName)
result = result.replace(/%cagithub%/g, doc.userGithub)
result = result.replace(/%creationdate%/g, d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear())
}
fs.writeFile('./src/components/' + componentName + '/' + fileName, result, function (err) {
if (err) return console.log(chalk.red(err))
console.log(chalk.green(fileName, 'created!'))
})
})
}
It looks in a folder called scaffold for the following files:
It then pulls the file into a cache, performs a find and replace on some strings and then writes the output to a file in the users project.
It seems though that whenever I try to reference the 'scaffold' folder, it's trying to find it in the users project folder and not in my package folder.
I'm very hesitant to reference the scaffold folder by writing '/node_modules/ctgen/scaffold' as that seems like the wrong thing to do to me.
What you want is __dirname.
If I understand your question, you have a ressource folder contained in your module, and have trouble accessing it since the current path is the path of the app, not your module.
__dirname will contain the path of your script file, and so will point to your module file.
I presume your module is named ctgen, and the files you want to access are in ctgen/scaffold. So in your code, try to access __dirname/scaffold.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With