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


当前回答

我知道关于“写”的问题,但在更一般的意义上,“附加”在某些情况下可能有用,因为它很容易在循环中使用,以便向文件中添加文本(无论文件是否存在)。如果要添加行,请使用“\n”,例如:

var fs = require('fs');
for (var i=0; i<10; i++){
    fs.appendFileSync("junk.csv", "Line:"+i+"\n");
}

其他回答

好的,这很简单,因为Node有内置的功能,它叫做fs,代表文件系统,基本上,NodeJS文件系统模块。。。

因此,首先需要在server.js文件中使用它,如下所示:

var fs = require('fs');

fs有几种方法可以写入文件,但我的首选方法是使用appendFile,这将把内容附加到文件中,如果文件不存在,将创建一个,代码如下:

fs.appendFile('myFile.txt', 'Hi Ali!', function (err) {
  if (err) throw err;
  console.log('Thanks, It\'s saved to the file!');
});

fs.createWriteStream(路径[,选项])选项还可以包括开始选项,以允许在文件开头之后的某个位置写入数据。修改文件而不是替换文件可能需要r+标志模式而不是默认模式w。编码可以是Buffer接受的任何一种。如果autoClose在“error”或“finish”时设置为true(默认行为),文件描述符将自动关闭。如果autoClose为false,则即使出现错误,也不会关闭文件描述符。应用程序负责关闭它并确保没有文件描述符泄漏。与ReadStream一样,如果指定了fd,WriteStream将忽略路径参数并使用指定的文件描述符。这意味着不会发出“打开”事件。fd应该是阻塞的;应将非阻塞fds传递给net.Socket。如果options是字符串,则它指定编码。

看完这篇长文。你应该了解它的工作原理。因此,这里有一个createWriteStream()的示例。

/* The fs.createWriteStream() returns an (WritableStream {aka} internal.Writeable) and we want the encoding as 'utf'-8 */
/* The WriteableStream has the method write() */
fs.createWriteStream('out.txt', 'utf-8')
.write('hello world');

文件系统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 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');
        })
    });
});

第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
  }
}