如何使用node.js和Promises在文件的特定行中添加一行

时间:2018-08-21 09:33:01

标签: node.js promise fs

情况:我编写了一些代码,循环遍历主目录及其子目录以查找htm文件,一旦找到.htm文件,则应在head标记后添加一行,然后应进一步循环查找所有内容主目录中的其他.htm文件,并且执行相同的操作。

代码:

var fs = require("fs");
var path = require("path");
var mainDirectory = 'directory';

function addLineInFile() { //execute the steps needed to alter the file's content in sequential order.
  readContent() //can be found below.
    .then(lookForHead) //can be found below.
    .then(writeNewContent) //can be found below.
}
addLineInFile();

function readContent() {
  return new Promise((resolve, reject) => {
    FileContent = [];
    fs.readFile(extendedDirectoryPath, (err, data) => {
      fileContent = data.toString('utf8').split("\n");
      console.log("Read file content")
    });
    if (err) {
      reject(err);
    } else {
      resolve(FileContent);
    }
  });
}

function lookForHead(FileContent) {
  return new Promise((resolve, reject) => {
    var string = "<head>"
    for (i = 0; i < FileContent.length; i++) {
      console.log("Looking for <head>.")
      if (FileContent[i].indexOf(string) !== -1) {
        console.log("found <head>")
        FileContent.splice(i + 1, 0, 'line to be added')
      }
    }
    if (err) {
      reject(err);
    } else {
      resolve(FileContent);
    }
  });
}

function writeNewContent(FileContent) {
  return new Promise((resolve, reject) => {
    console.log("Started Writing to the file!")
    var file = fs.createWriteStream(extendedDirectoryPath);
    file.on('error', function(err) { /* error handling */ });
    FileContent.forEach(function(v) {
      file.write(v.join(', ') + '\n');
      console.log("Wrote a line to the file.")
    });
    file.end();
    if (err) {
      reject(err);
    } else {
      resolve(FileContent);
    }
  });
}

问题:文件已写入之前,已经准备好要写入的内容(请看一下输出)。因此,在将readContent()和lookForHead()赋予其要写入文件中的内容之前,执行writeNewContent()。在此之前,我已经尝试了很多不同的事情,例如回调函数,并确信Promises是我的解决方案,但是也许我使用的方式不正确?请记住,我对node.js不太了解,并且许诺我的大部分工作只是从Internet复制粘贴并将其一小部分更改为我喜欢的。

输出:

Got file info successfully!
file1.htm This is an htm file!
Started Writing to the file!
Got file info successfully!
file2.htm This is an htm file!
Started Writing to the file!
Got file info successfully!
file3.htm This is an htm file!
Started Writing to the file!
Got file info successfully!
file4.htm This is an htm file!
Started Writing to the file!
Got file info successfully!
someInnerDirectory is a innerDirectory
Delving deeper!
Got file info successfully!
file5.htm This is anhtm file!
Started Writing to the file!
Got file info successfully!
file6.htm This is an htm file!
Started Writing to the file!
Got file info successfully!
file7.htm This is an htm file!
Started Writing to the file!
Read file content
Read file content
Read file content
Read file content
Read file content
Read file content
Read file content

1 个答案:

答案 0 :(得分:0)

到目前为止,您的工作做得很好,并且坚持下去。很高兴看到您也在使用递归。您正在创建一个名为addLineInFile的函数,但不执行它。 I did something similar a while back, check it out