I wanted to turn a simple function into a module I could require in another project. I wanted to read in txt files, using promisify (bluebird) to fs.readFile. Using Promise.promisify works, but the result is only the contents of the file. I needed the contents AND filename. So I decided to try and promisify the call myself and then wrap the functionality into a separate module I could pull in from github.
Creating the module
Basically you’ll need 2 files… a file for the functionality and a package.json file. The slightly tricky part was the package.json. I forgot to add the main section, so when I tried importing it into my project, there was an error about an undefined function. Here is a very stripped down version of my package.json file:
{
"name": "fs_readfile",
"main": "lib/read_file.js",
"dependencies": {
"bluebird": "~3.4.6"
}
}
This is the module I created: fs_readfile. It uses bluebird to return a promise for fs.readFile and in the promise, returns the filename, filepath, and contents of the file. I’m sure there’s a module out there that does this, but I wanted to try writing this myself.
Importing the module from github
Now that I have that module on github, I want to use it in my project, so I added that module as a dependency.
"fs_readfile": "git://github.com/lynzt/fs_readfile.git"
Remember to npm install
Then require the module and use it like you would any other module:
const readFile = require("fs_readfile");
readFile.readFileAdditionalInfo(path, name, "utf8").then(file => {
console.dir(file);
}
This article is similar to one I wrote about installing python modules from github…