用 Node.js 编写文件

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?

转载于:https://stackoverflow.com/questions/2496710/writing-files-in-node-js

12个回答

There are a lot of details in the filesystem API. The most common way (as far as I know) is:

var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 
csdnceshi56
lrony* Or ES2015 async/await style: await promisify(fs.writeFile)("./test.md", markdownFile);
接近 3 年之前 回复
csdnceshi68
local-host “Note that it is unsafe to use fs.writeFile multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.”
大约 3 年之前 回复
weixin_41568184
叼花硬汉 "./file.txt" will be written in current directory.
3 年多之前 回复
csdnceshi73
喵-见缝插针 How is it possible to write on the current directory?
3 年多之前 回复
csdnceshi72
谁还没个明天 At least with ECMAScript 6, fs.writeFile is deprecated. Not sure what has replaced it.
3 年多之前 回复
csdnceshi51
旧行李 Do you need to fs.close() when finished?
接近 5 年之前 回复
csdnceshi74
7*4 This seems to write to file? What's the version to append to file?
5 年多之前 回复
csdnceshi76
斗士狗 I'm trying to do this to an ascii based file and null characters are getting inserted into every other character. Advice?
6 年多之前 回复
csdnceshi77
狐狸.fox Well, since he wanted to save the file on /home directory I suggested to chmod it. I know it could generate a security issue. But well, if the user wants to save there, that's the solution. P.S: I agree with what you said (:
6 年多之前 回复
csdnceshi64
游.程 Actually, @DenysVitali, the problem is that jane should not be able to write any files into /home/.... Generally that directory is 755 root:wheel (or whatever). If node wants to write a file as jane, it's going to be easier to write to /home/jane/test.txt. Changing /home to something more permissive than 755 is a huge mistake.
接近 7 年之前 回复
csdnceshi77
狐狸.fox Maybe it's a bit old, but @AndersonGreen, you need to run node as root or chmod /home properly to allow R/W permissions to current node process owner (your username tough) so you can write the file
接近 7 年之前 回复
weixin_41568127
?yb? Also note you can use fs.writeFileSync(...) to accomplish the same thing synchronously.
接近 8 年之前 回复
weixin_41568208
北城已荒凉 I've tested this script using Node, and I tried changing the file path to "/home/", but I got the following error: { [Error: EACCES, open '/home/test.txt'] errno: 3, code: 'EACCES', path: '/home/test.txt' } How can I modify this script so that it will work outside of /tmp?
大约 8 年之前 回复

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();
});
csdnceshi54
hurriedly% You will have to wait for it.
接近 6 年之前 回复
csdnceshi59
ℙℕℤℝ Does the 'open' event happen asynchronously? Do I have to wait for it, or can I start writing into the stream immediately?
接近 7 年之前 回复
csdnceshi54
hurriedly% I'm not sure if when the stream is flushed. My guess is that there is a possibility to flush the stream on demand.
7 年多之前 回复
weixin_41568183
零零乙 Will this fail if the server goes down before stream.end() is called? In essence, can I use this for error logging to specific file? (Yes, I know you can specify this when you run the node app, but for certain errors I want to store it in a different file than all the other logging).
7 年多之前 回复
csdnceshi54
hurriedly% You can always do a stream.end() when you've done your stream.writes(). I will add it to the example.
接近 8 年之前 回复
csdnceshi65
larry*wei When do I close the stream? Why is this non-blocking? Just curious, I am trying to write to a log file.
接近 8 年之前 回复
weixin_41568110
七度&光 file descriptor so you will be able to close stream after you've done with it.
接近 8 年之前 回复
weixin_41568196
撒拉嘿哟木头 What is the 'fd' variable passed into the callback for stream.once ?
大约 8 年之前 回复

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.

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 n times, and at time n+1, the stream sends the buffer to the kernel (because it's full and needs to be flushed).

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 WriteStream inherits from a writable Stream object. If you pay attention, you’ll see how they flush the content; they don't have any buffering system.

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 three calls 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.

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.

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.

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

csdnceshi54
hurriedly% As of now, Node v0.12 is stable.
5 年多之前 回复
csdnceshi57
perhaps? any chance you could provide an example of how to use cork() and uncork() for those of us who want to try out the pre-release 0.11 node?
大约 6 年之前 回复
csdnceshi64
游.程 +1 - nice explanation. For write stream, it's important to read the docs carefully. If returns false or closing, important to call writer.once('drain', function(){}) or I missed lines that hadn't drained when the process ended.
6 年多之前 回复

Synchronous Write

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

fs = require('fs');

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

Asynchronous Write

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

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.

 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");
                            });
                        }
                });
csdnceshi53
Lotus@ Where you are writting the data into the "to.text"??
3 年多之前 回复

Here we use w+ for read/write both actions and if the file path is not found the it would be created automatically.

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 means what you have to write to the file and its length, 'content.length'.

Here is the sample of how to read file csv from local and write csv file to local.

var csvjson = require('csvjson'),
    fs = require('fs'),
    mongodb = require('mongodb'),
    MongoClient = mongodb.MongoClient,
    mongoDSN = 'mongodb://localhost:27017/test',
    collection;

function uploadcsvModule(){
    var data = fs.readFileSync( '/home/limitless/Downloads/orders_sample.csv', { encoding : 'utf8'});
    var importOptions = {
        delimiter : ',', // optional 
        quote     : '"' // optional 
    },ExportOptions = {
        delimiter   : ",",
        wrap        : false
    }
    var myobj = csvjson.toSchemaObject(data, importOptions)
    var exportArr = [], importArr = [];
    myobj.forEach(d=>{
        if(d.orderId==undefined || d.orderId=='') {
            exportArr.push(d)
        } else {
            importArr.push(d)
        }
    })
    var csv = csvjson.toCSV(exportArr, ExportOptions);
    MongoClient.connect(mongoDSN, function(error, db) {
        collection = db.collection("orders")
        collection.insertMany(importArr, function(err,result){
            fs.writeFile('/home/limitless/Downloads/orders_sample1.csv', csv, { encoding : 'utf8'});
            db.close();
        });            
    })
}

uploadcsvModule()

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

It worked for me.

See also How do I write files in 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:

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.

csdnceshi53
Lotus@ I just found it. Using this ROOT_APP_PATH = fs.realpathSync('.'); console.log(ROOT_APP_PATH); to get my where the file written. Thanks.
接近 6 年之前 回复
csdnceshi75
衫裤跑路 node test.js cat helloworld.txt Hello World!
接近 6 年之前 回复
csdnceshi53
Lotus@ That's weird... I just can't find it anywhere. Will it be hidden? thanks again~
接近 6 年之前 回复
csdnceshi75
衫裤跑路 in folder that you run the script
接近 6 年之前 回复
csdnceshi53
Lotus@ Where to find the file helloworld.txt ? I can't find it in any folders... thanks.
接近 6 年之前 回复

You can use library easy-file-manager

install first from npm npm install easy-file-manager

Sample to upload and remove files

var filemanager = require('easy-file-manager')
var path = "/public"
var filename = "test.jpg"
var data; // buffered image

filemanager.upload(path,filename,data,function(err){
    if (err) console.log(err);
});

filemanager.remove(path,"aa,filename,function(isSuccess){
    if (err) console.log(err);
});
csdnceshi80
胖鸭 This modules is created to save and remove files.. Not an answer.
大约 4 年之前 回复

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:

var fs = require('fs');
for (var i=0; i<10; i++){
    fs.appendFileSync("junk.csv", "Line:"+i+"\n");
}
weixin_41568127
?yb? fixed, thanks 0x48piraj
2 年多之前 回复
csdnceshi79
python小菜 It should be var fs = require('fs');, Right?
2 年多之前 回复
共12条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐