项目作者: jalal246

项目描述 :
Replace text in a given file.
高级语言: JavaScript
项目地址: git://github.com/jalal246/replace-in.git
创建时间: 2017-07-24T13:19:36Z
项目社区:https://github.com/jalal246/replace-in

开源协议:MIT License

下载


replace-in

Replace text in a given file.

  1. npm install replace-in

How it works?

It creates a read stream to read from the target file in chunks. Replace each
request and write the results using write stream. A final report will be
returned when the replacement is done.

API

replace(options)

options object contains:

  • path: string file path
  • request: array array of objects. Each object must have two properties:
    • regex for RegExp/String to be matched.
    • replace string replacement.
  • encoding:? string read stream encoding (default: utf8)

The results is promise contains report: array An array of objects. Each element contains three keys:

  • isChanged: Boolean search result.
  • regex: string regex sent in the request.
  • replace: string replacement sent in the request.

Example

  1. const replace = require("replace-in");
  2. // let's create some phrases to replace it in our file.
  3. const phrase1 = {
  4. // regex
  5. regex: /old/gi,
  6. // replace
  7. replace: "new",
  8. };
  9. // and we have to replace more.
  10. const phrase1 = {
  11. // regex
  12. regex: "second",
  13. // replace
  14. replace: "third",
  15. };
  16. const report = await replace({
  17. path: "/path1/path2/fileName",
  18. request: [phrase1, phrase1],
  19. });
  20. // > report
  21. // [
  22. // {
  23. // isChanged: true,
  24. // regex: /old/gi,
  25. // replace: "new",
  26. // },
  27. // {
  28. // isChanged: false, // not found so it wasn't changed
  29. // regex: "second",
  30. // replace: "third",
  31. // },
  32. // ];

Or you can check specific phrase result:

  1. const report = await replace({
  2. path: "/path1/path2/fileName",
  3. request: [phrase1, phrase1],
  4. });
  5. if (report[2].isChanged) {
  6. console.log("phrase1 was found and changed");
  7. } else {
  8. console.log("phrase1 was not found in the file!");
  9. }

Tests

  1. test
  • find-in - A tool, written in JS
    for Searching Text in Files.
  • textics &
    textics-stream - counts lines, words, chars and spaces for a given string.

  • packageSorter - Sorting packages
    for monorepos production.

  • move-position - Moves element in
    given array form index-A to index-B.

License

This project is licensed under the MIT License