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


当前回答

您可以使用流写入文件。

就这样做:

const fs = require('fs');

const stream = fs.createWriteStream('./test.txt');
stream.write("Example text");

其他回答

我喜欢的索引/文章/文件系统。

这对我有用。

另请参阅如何在node.js中写入文件?。

fs = require('fs');
fs.writeFile('helloworld.txt', 'Hello World!', function (err) {
    if (err) 
        return console.log(err);
    console.log('Wrote Hello World in file helloworld.txt, just check it');
});

helloworld.txt的内容:

Hello World!

更新:就像在当前目录中写入Linux节点一样,在其他一些目录中似乎没有,所以我添加了这条注释,以防万一:使用此ROOT_APP_PATH=fs.realpathSync('.');console.log(ROOT_APP_PATH);以获取文件的写入位置。

好的,这很简单,因为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!');
});

您可以使用流写入文件。

就这样做:

const fs = require('fs');

const stream = fs.createWriteStream('./test.txt');
stream.write("Example text");

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