我一直在尝试在使用Node.js时写入文件,但没有成功。我该怎么做?


当前回答

提供的答案已注明日期,更新的方法是:

const fsPromises = require('fs').promises
await fsPromises.writeFile('/path/to/file.txt', 'data to write')

有关详细信息,请参阅此处的文档

其他回答

文件系统API中有很多细节。最常见的方法是:

const fs = require('fs');

fs.writeFile("/tmp/test", "Hey there!", function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved!");
}); 

// Or
fs.writeFileSync('/tmp/test-sync', 'Hey there!');

您可以通过以下代码示例写入文件:

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.');
      }
    });
  }
});
var path = 'public/uploads/file.txt',
buffer = new Buffer("some content\n");

fs.open(path, 'w', function(err, fd) {
    if (err) {
        throw 'error opening file: ' + err;
    }

    fs.write(fd, buffer, 0, buffer.length, null, function(err) {
        if (err) throw 'error writing file: ' + err;
        fs.close(fd, function() {
            console.log('file written');
        })
    });
});

你当然可以让它更高级一点。非阻塞、写入位和段,而不是一次写入整个文件:

var fs = require('fs');
var stream = fs.createWriteStream("my_file.txt");
stream.once('open', function(fd) {
  stream.write("My first row\n");
  stream.write("My second row\n");
  stream.end();
});

第1点:

如果你想写一些东西到文件中。意思是:它将删除文件中已保存的任何内容并写入新内容。使用fs.promise.writeFile()

第2点:

如果您想将某个内容附加到文件中。意思是:它不会删除文件中已保存的任何内容,而是将新项附加到文件内容中。然后首先读取文件,然后将内容添加到可读值中,然后将其写入文件。所以使用fs.promises.readFile和fs.promists.writeFile()


示例1:我想在JSON文件中编写一个JSON对象。

const fs = require('fs');
const data = {table:[{id: 1, name: 'my name'}]}
const file_path = './my_data.json'
writeFile(file_path, data)
async function writeFile(filename, writedata) {
  try {
    await fs.promises.writeFile(filename, JSON.stringify(writedata, null, 4), 'utf8');
    console.log('data is written successfully in the file')
  }
  catch (err) {
    console.log('not able to write data in the file ')
  }
}

示例2:如果要将数据附加到JSON文件中。您希望将数据{id:1,name:‘my name’}添加到同一文件夹根目录下的文件mydata.json中。只需调用appenddata(filepath,data)函数。

如果文件存在,它将在JSON文件中附加数据。或者它将创建文件并将数据添加到其中。

const fs = require('fs');
const data = {id: 2, name: 'your name'}
const file_path = './my_data.json'
append_data(file_path, data)

async function append_data(filename, data) {

  if (fs.existsSync(filename)) {
    var read_data = await readFile(filename)
    if (read_data == false) {
      console.log('not able to read file')
    } else {
      read_data.table.push(data)  //data must have the table array in it like example 1
      var dataWrittenStatus = await writeFile(filename, read_data)
      if (dataWrittenStatus == true) {
        console.log('data added successfully')
      } else {
        console.log('data adding failed')
      }
    }
  }
}

async function readFile(filePath) {
  try {
    const data = await fs.promises.readFile(filePath, 'utf8')
    return JSON.parse(data)
  }
  catch (err) {
    return false;
  }
}

async function writeFile(filename, writedata) {
  try {
    await fs.promises.writeFile(filename, JSON.stringify(writedata, null, 4), 'utf8');
    return true
  }
  catch (err) {
    return false
  }
}