MENU

nodejs 文件读写

October 19, 2019 • 默认分类

封装 fs 模块

快速读写,支持大文件读写,支持自动关闭close

class FileUtils

const fs = require('fs')
const path = require('path')

class FileUtils {
    constructor() {

    }

    checkFile(path) {
        return new Promise((resolve, reject) => {
            try {
                let result = fs.existsSync(path);
                if (result) {
                    resolve(true)
                } else {
                    resolve(false)
                }
            } catch (e) {
                reject(e)
            }
        });
    }

    readFile(path, opts = 'utf8mb4') {
        return new Promise((resolve, reject) => {
            try {
                var input = fs.createReadStream(path, {
                    encoding: 'utf8mb4',
                    autoClose: true,
                });

                var remaining = '';

                input.on('data', function (data) {
                    remaining += data;
                    var index = remaining.indexOf('\n');
                    var last = 0;
                    while (index > -1) {
                        var line = remaining.substring(last, index);
                        last = index + 1;
                        func(line);
                        index = remaining.indexOf('\n', last);
                    }

                    remaining = remaining.substring(last);
                });

                input.on('end', function () {
                    resolve(remaining)
                });
            } catch (e) {
                console.error('Error writeObjectToJsonString:', e);
                resolve(e)
            }

        })
    }

    writeFile(path, data, opts = 'utf8mb4') {
        return new Promise((resolve, reject) => {
            var out = undefined;
                 out = fs.createWriteStream(path, {
                    encoding: 'utf8mb4'
                });
                out.write(data,(error) => {
                    if (error) {
                        reject(error)
                    } else {
                        resolve()
                    }
                });
                out.end();

        })
    }

    mkdirs(dirname) {
        return new Promise((resolve, reject) => {
            if (!fs.existsSync(dirname)) {
                fs.mkdir(dirname, {recursive: true}, (err) => {
                    if (err) {
                        reject(err)
                    } else {
                        resolve()
                    }
                });
            } else {
                resolve();
            }

        });

    }
}

module.exports = new FileUtils();