Writing files in Node.js

前端 未结 19 2078
情歌与酒
情歌与酒 2020-11-21 11:57

I\'ve been trying to find a way to write to a file when using Node.js, but with no success. How can I do that?

19条回答
  •  我寻月下人不归
    2020-11-21 12:11

    You can write in a file by the following code example:

    var data = [{ 'test': '123', 'test2': 'Lorem Ipsem ' }];
    fs.open(datapath + '/data/topplayers.json', 'wx', function (error, fileDescriptor) {
      if (!error && fileDescriptor) {
        var stringData = JSON.stringify(data);
        fs.writeFile(fileDescriptor, stringData, function (error) {
          if (!error) {
            fs.close(fileDescriptor, function (error) {
              if (!error) {
                callback(false);
              } else {
                callback('Error in close file');
              }
            });
          } else {
            callback('Error in writing file.');
          }
        });
      }
    });
    

提交回复
热议问题