Node.js将数据写入文件会引发错误

时间:2019-07-14 16:27:48

标签: node.js

运行程序时收到此错误 TypeError:回调不是函数

// Update data from a new file

lib.update = function(dir,file,callback){
    //Open the file for writing

    fs.open(lib.baseDir+dir+'/'+'.json','r+',function(err,fileDescriptor){
        if(!err && fileDescriptor){
            var stringData= JSON.stringify(data);

            //Truncate the file before writing

            fs.truncate(fileDescriptor,function(err){
                if(!err){
                    //Write to the file and close it
                    fs.writeFile(fileDescriptor,stringData,function(err){
                        if(!err){
                            fs.close(fileDescriptor,function(err){
                                if(!err){
                                    callback(false);
                                }else {
                                    callback('Error closing existing file!')
                                }
                            })
                        }else {
                            callback('Error writing to existing file')
                        }
                    });
                }else {
                    callback('Error Truncating file')
                }
            });
        }else {
            callback('Could not open file for updating! May not exist yet')
        }
    });
}

1 个答案:

答案 0 :(得分:0)

我建议您重构代码,以更清楚地了解自己在做什么。诸如此类,它将帮助您找到错误的出处。使用promise比使用大量回调要好。

只有我的贡献。

lib.update = function(dir, file, data) {
  const updateP = new CustomPromise();

  openFile()
    .then(truncateFile)
    .then(writeFile.bind(this, JSON.stringify(data)))
    .then(closeFile)
    .then(updateP.resolve) // at this point all the functions was successful
    .catch((errorType) =>
      errorType !== ERROR_TYPE.ERROR_CLOSING_FILE // something fail try to close the file
        ? closeFile().finally(() => updateP.reject(errorType))
        : updateP.reject(errorType),
    );

  return updateP.promise;
};

// Constants

const ERROR_TYPE = Object.freeze({
  ERROR_OPEN_FILE: 'error-open-file',
  ERROR_TRUNCATING_FILE: 'error-truncating-file',
  ERROR_WRITING_FILE: 'error-writing-file',
  ERROR_CLOSING_FILE: 'error-closing-file',
});

// Private functions

function CustomPromise() {
  this.promise = new Promise(function(resolve, reject) {
    this.resolve = resolve;
    this.reject = reject;
  });
}

function openFile() {
  const openP = new CustomPromise();

  fs.open(lib.baseDir + dir + '/' + '.json', 'r+', function(err, fileDescriptor) {
    (err || !fileDescriptor) && openP.reject(ERROR_TYPE.ERROR_OPEN_FILE);
    openP.resolve(fileDescriptor);
  });

  return openP.promise;
}

function truncateFile(fileDescriptor) {
  const truncateP = new CustomPromise();

  fs.truncate(fileDescriptor, function(err) {
    err && truncateP.reject(ERROR_TYPE.ERROR_TRUNCATING_FILE);
    truncateP.resolve(fileDescriptor);
  });

  return truncateP.promise;
}

function writeFile(data, fileDescriptor) {
  const writeFileP = new CustomPromise();

  fs.writeFile(fileDescriptor, data, function(err) {
    err && writeFileP.reject(ERROR_TYPE.ERROR_WRITING_FILE);
    writeFileP.resolve(fileDescriptor);
  });

  return writeFileP.promise;
}

function closeFile(fileDescriptor) {
  const closeP = new CustomPromise();
  fs.close(fileDescriptor, function(err) {
    err && closeP.reject(ERROR_TYPE.ERROR_CLOSING_FILE);
    closeP.resolve();
  });

  return closeP.promise;
}