๐ก Want to reuse common string operations like
capitalize()
or slugify()
across projects? Learn how to create and publish your own Node.js utility package!
๐ Project Structure
custom-package/
├── index.js
├── package.json
├── README.md
└── utils/
├── capitalize.js
├── camelCase.js
├── slugify.js
└── greeting.js
✅ Initialize the Package
npm init -y
This creates a package.json
with default values.
๐งฉ Write Utility Functions
utils/capitalize.js
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
module.exports = capitalize;
utils/camelCase.js
function camelCase(str) {
return str
.replace(/\s(.)/g, (match, group1) => group1.toUpperCase())
.replace(/\s/g, '')
.replace(/^(.)/, (match, group1) => group1.toLowerCase());
}
module.exports = camelCase;
utils/slugify.js
function slugify(str) {
return str
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.trim()
.replace(/[\s_-]+/g, '-');
}
module.exports = slugify;
utils/greeting.js
function sayHello(name) {
return `Hello, ${name}!`;
}
module.exports = sayHello;
๐งฉ Create the Package Entry Point
index.js
const capitalize = require('./utils/capitalize');
const camelCase = require('./utils/camelCase');
const slugify = require('./utils/slugify');
const sayHello = require('./utils/greeting');
module.exports = {
capitalize,
camelCase,
slugify,
sayHello
};
๐งช Test Your Package Locally
Step 1: Link your package globally
npm link
Step 2: Create a test project
mkdir test-custom-package
cd test-custom-package
npm init -y
Step 3: Link your custom package
npm link custom-package
Step 4: Write a test file
// index.js
const utils = require('custom-package');
console.log(utils.sayHello('Rana')); // Hello, Rana!
console.log(utils.capitalize('world')); // World
console.log(utils.camelCase('hello world app')); // helloWorldApp
console.log(utils.slugify('Node.js String Utils')); // node-js-string-utils
Step 5: Run the file
node index.js
๐ Optional: Publish to npm
1. Login to npm
npm login
2. Rename your package (if needed)
Use a unique name or scoped name like @yourname/custom-package
.
3. Publish it
npm publish --access public
๐ฏ Final Thoughts
Creating a custom utility package in Node.js is a practical way to:
- Promote code reuse
- Practice modular architecture
- Contribute to open-source
- Impress recruiters or collaborators
Tip: Even simple utilities can add real value when published thoughtfully.
๐ View Full Code on GitHub
Comments
Post a Comment