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


当前回答

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!');

在这里,我们使用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”。

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

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

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

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

这对我有用。

另请参阅如何在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);以获取文件的写入位置。

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

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