read-modify-write
NodeJS - Read File, Modify Content, Write to File
Table of content
- Introduction to read-modify-write
- Read File/Directory
- Write to File/Directory
- Filter files
- Modify Content
- Prepare for Production
- Run tests
1. Introduction to read-modify-write
This Node module provides an API to interact with the file system and perform recursive sequential IO operations (such as file reading/writing and file content modification). It executes all operations in a blocking and synchronous way. It is a very simple yet very flexible toolkit with size of less than 2KB and no dependencies. To use the library all we need is to import read-modify-write module into our code.
const rmw = ;
2. Read File/Directory
To read file content recursively in a chosen directory we simply need to pass the folder path as the first parameter to the already imported module:
;
3. Write to File/Directory
To copy files from one directory to another we need a path modifier function which is passed as a second parameter:
const move = filePath;;
The path modifier function takes one parameter which is the location / path for each of the listed files. The code above copies all files in the 'src/dummy' folder to the 'dist/dummy'.
4. Filter files
To filter files with certain extension we need to supply a function that will be called on each files on the list, and only return the values that pass a specific test (in this case the file extension is present in the string):
const move = filePath;const filterHtml = c;;
This function, in combination with the previous one can be used to add suffix for certain file types:
const move = filePath;const filterJs = c;;
5. Modify files
Consider an html file in 'src' folder with the following content:
To update the file content and save it to a new location we need to pass a forth parameter which is an update function which accepts file content as an argument.
const move = filePath;const filterHtml = c;const update = c;;
The code above will result in a new html file created in the 'dist/dummy' folder with the following content:
6. Prepare for production
This toolkit can assist you automate painful or time-consuming tasks in your development workflow. For example when publishing to production it can help you by doing CSS preprocessing, JS transpiling, minification, and much more:
const terser = ;const cleanCss = ;const uglify = terser;const clean = styles;const move = filePath;const filterJs = c;const filterCss = c;;s;;
7. Running tests
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can run the tests the following command:
$ npm test