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


当前回答

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

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

其他回答

在这里,我们使用w+来读取/写入这两个操作,如果找不到文件路径,那么它将自动创建。

fs.open(path, 'w+', function(err, data) {
    if (err) {
        console.log("ERROR !! " + err);
    } else {
        fs.write(data, 'content', 0, 'content length', null, function(err) {
            if (err)
                console.log("ERROR !! " + err);
            fs.close(data, function() {
                console.log('written success');
            })
        });
    }
});

内容是指您必须写入文件的内容及其长度“Content.length”。

 var fs = require('fs');
 fs.writeFile(path + "\\message.txt", "Hello", function(err){
 if (err) throw err;
  console.log("success");
}); 

例如:读取文件并写入另一个文件:

  var fs = require('fs');
    var path = process.cwd();
    fs.readFile(path+"\\from.txt",function(err,data)
                {
                    if(err)
                        console.log(err)
                    else
                        {
                            fs.writeFile(path+"\\to.text",function(erro){
                                if(erro)
                                    console.log("error : "+erro);
                                else
                                    console.log("success");
                            });
                        }
                });
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');
        })
    });
});

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

这对我有用。

另请参阅如何在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!');
});