zoukankan      html  css  js  c++  java
  • node中fileSystem改promise

    请注意,fs的大部分函数回调只会返回一个error参数,所以只要判断error为false的情况下就返回成功,无论有没有第二个参数。
    另外exists需要单独包装,因为第一个参数就代表返回内容

    
    const fs = require('fs');
    const ab = ['access', 'rename', 'ftruncate', 'chown', 'lchown', 'cmod', 'fchmod', 'stat', 'lstat', 'fstat', 'link', 'symlink',
        'readlink', 'realpath', 'unlink', 'rmdir', 'readdir', 'close', 'open', 'utimes',
        'futimes', 'fsync', 'write', 'read', 'readFile', 'writeFile', 'appendFile', 'mkdir', 'mkdtemp']
    // fchown fdatasync mkdtemp rename truncate
    ab.forEach(name => {
        if (!fs[name])return;
        exports[name] = (...n) => {
            return new Promise((res, rej) => {
                fs[name](...n, (er,d) => {
                    // 这里判断请注意不要去判断d参数
                    if (er) rej(er)
                    else res(d)
                })
            })
        }
    })
    
    exports.exists = (path) => {
        return new Promise((res, rej) => {
            fs.exists(path, (exists) => {
                res(exists);
            })
        });
    }
    
  • 相关阅读:
    JVM内存模型
    052-224(新增70题2018)
    052-223(新增70题2018)
    052-222(新增70题2018)
    052-221(新增70题2018)
    052-220(新增70题2018)
    052-219(新增70题2018)
    052-218(新增70题2018)
    052-217(新增70题2018)
    052-216(新增70题2018)
  • 原文地址:https://www.cnblogs.com/liuyt/p/7371940.html
Copyright © 2011-2022 走看看