Javascript 在 Node.js 中编写文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2496710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:39:09  来源:igfitidea点击:

Writing files in Node.js

javascriptnode.jsfileexpressfs

提问by Gjorgji

I've been trying to find a way to write to a file when using Node.js, but with no success. How can I do that?

我一直试图找到一种在使用 Node.js 时写入文件的方法,但没有成功。我怎样才能做到这一点?

回答by Brian McKenna

There are a lot of details in the File System API. The most common way is:

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

回答by Gabriel Llamas

Currently there are three ways to write a file:

目前有三种写文件的方式:

  1. fs.write(fd, buffer, offset, length, position, callback)

    You need to wait for the callback to ensure that the buffer is written to disk. It's not buffered.

  2. fs.writeFile(filename, data, [encoding], callback)

    All data must be stored at the same time; you cannot perform sequential writes.

  3. fs.createWriteStream(path, [options])

    Creates a WriteStream, which is convenient because you don't need to wait for a callback. But again, it's not buffered.

  1. fs.write(fd, buffer, offset, length, position, callback)

    您需要等待回调以确保将缓冲区写入磁盘。它没有缓冲。

  2. fs.writeFile(filename, data, [encoding], callback)

    所有数据必须同时存储;您不能执行顺序写入。

  3. fs.createWriteStream(path, [options])

    创建一个WriteStream,这很方便,因为您不需要等待回调。但同样,它没有缓冲。

A WriteStream, as the name says, is a stream. A stream by definition is “a buffer” containing data which moves in one direction (source ? destination). But a writable stream is not necessarily “buffered”. A stream is “buffered” when you write ntimes, and at time n+1, the stream sends the buffer to the kernel (because it's full and needs to be flushed).

A WriteStream,顾名思义,是一个流。根据定义,流是“缓冲区”,其中包含沿一个方向(源 ? 目的地)移动的数据。但是可写流不一定是“缓冲的”。当您写入n时间时,流被“缓冲” ,并且在 time 时n+1,流将缓冲区发送到内核(因为它已满并且需要刷新)。

In other words:“A buffer” is the object. Whether or not it “is buffered” is a property of that object.

换句话说:“缓冲区”是对象。它是否“被缓冲”是该对象的一个​​属性。

If you look at the code, the WriteStreaminherits from a writable Streamobject. If you pay attention, you'll see how they flush the content; they don't have any buffering system.

如果您查看代码,就会发现它WriteStream继承自一个可写Stream对象。如果你注意,你会看到他们如何刷新内容;他们没有任何缓冲系统。

If you write a string, it's converted to a buffer, and then sent to the native layer and written to disk. When writing strings, they're not filling up any buffer. So, if you do:

如果你写一个字符串,它会被转换成一个缓冲区,然后发送到本机层并写入磁盘。写入字符串时,它们不会填满任何缓冲区。所以,如果你这样做:

write("a")
write("b")
write("c")

You're doing:

你正在做的:

fs.write(new Buffer("a"))
fs.write(new Buffer("b"))
fs.write(new Buffer("c"))

That's threecalls to the I/O layer. Although you're using “buffers”, the data is not buffered. A buffered stream would do: fs.write(new Buffer ("abc")), one call to the I/O layer.

这是对 I/O 层的三个调用。尽管您使用了“缓冲区”,但数据并未被缓冲。缓冲流可以:fs.write(new Buffer ("abc")),对 I/O 层的一次调用。

As of now, in Node.js v0.12 (stable version announced 02/06/2015) now supports two functions: cork()and uncork(). It seems that these functions will finally allow you to buffer/flush the write calls.

截至目前,Node.js v0.12(稳定版于 2015 年 2 月 6 日发布)现在支持两个功能: cork()uncork(). 似乎这些函数最终将允许您缓冲/刷新写入调用。

For example, in Java there are some classes that provide buffered streams (BufferedOutputStream, BufferedWriter...). If you write three bytes, these bytes will be stored in the buffer (memory) instead of doing an I/O call just for three bytes. When the buffer is full the content is flushed and saved to disk. This improves performance.

例如,在 Java 中有一些类提供缓冲流(BufferedOutputStreamBufferedWriter...)。如果写入三个字节,这些字节将存储在缓冲区(内存)中,而不是仅对三个字节进行 I/O 调用。当缓冲区已满时,内容将被刷新并保存到磁盘。这提高了性能。

I'm not discovering anything, just remembering how a disk access should be done.

我没有发现任何东西,只是记得应该如何进行磁盘访问。

回答by Fredrik Andersson

You can of course make it a little more advanced. Non-blocking, writing bits and pieces, not writing the whole file at once:

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

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();
});

回答by Moriarty

Synchronous Write

同步写入

fs.writeFileSync(file, data[, options])

fs.writeFileSync(文件,数据[,选项])

fs = require('fs');

fs.writeFileSync("synchronous.txt", "synchronous write!")

Asynchronous Write

异步写入

fs.writeFile(file, data[, options], callback)

fs.writeFile(文件,数据[,选项],回调)

fs = require('fs');

fs.writeFile('asynchronous.txt', 'asynchronous write!', (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});

Where

在哪里

file <string> | <Buffer> | <URL> | <integer> filename or file descriptor
data <string> | <Buffer> | <Uint8Array>
options <Object> | <string>
callback <Function>

Worth reading the offical File System (fs) docs.

值得阅读官方文件系统 (fs)文档

回答by Mister P

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

回答by Sérgio

I liked Index of ./articles/file-system.

我喜欢./articles/file-system 的索引

It worked for me.

它对我有用。

See also How do I write files in node.js?.

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

Contents of helloworld.txt:

helloworld.txt 的内容:

Hello World!

Update:
As in Linux node write in current directory , it seems in some others don't, so I add this comment just in case :
Using this ROOT_APP_PATH = fs.realpathSync('.'); console.log(ROOT_APP_PATH);to get where the file is written.

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

回答by TrevTheDev

The answers provided are dated and a newer way to do this is:

提供的答案已过时,更新的方法是:

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

see documents here for more info

有关更多信息,请参阅此处的文档

回答by Astra Bear

I know the question asked about "write" but in a more general sense "append" might be useful in some cases as it is easy to use in a loop to add text to a file (whether the file exists or not). Use a "\n" if you want to add lines eg:

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

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

回答by Alireza

OK, it's quite simple as Node has built-in functionality for this, it's called fswhich stands for File Systemand basically, NodeJS File System module...

OK,这是因为节点具有内置的功能,这很简单,这就是所谓的fs它代表的文件系统而言基本上的NodeJS文件系统模块...

So first require it in your server.jsfile like this:

所以首先在你的server.js文件中像这样要求它:

var fs = require('fs');

fshas few methods to do write to file, but my preferred way is using appendFile, this will append the stuff to the file and if the file doesn't exist, will create one, the code could be like below:

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

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

回答by Masoud Siahkali

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

For example : read file and write to another file :

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

  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");
                            });
                        }
                });