How to append to a file in Node?

后端 未结 18 1256
庸人自扰
庸人自扰 2020-11-22 09:23

I am trying to append a string to a log file. However writeFile will erase the content each time before writing the string.

fs.writeFile(\'log.txt\'         


        
18条回答
  •  长发绾君心
    2020-11-22 10:11

    I wrapped the async fs.appendFile into a Promise-based function. Hope it helps others to see how this would work.

        append (path, name, data) {
    
            return new Promise(async (resolve, reject) => {
    
                try {
    
                    fs.appendFile((path + name), data, async (err) => {
    
                        if (!err) {
    
                            return resolve((path + name));
    
                        } else {
    
                            return reject(err);
    
                        }
    
                    });
    
                } catch (err) {
    
                    return reject(err);
    
                }
    
            });
    
        }
    

提交回复
热议问题