Writing files in Node.js

前端 未结 19 2022
情歌与酒
情歌与酒 2020-11-21 11:57

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?

19条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 12:06

    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'.

提交回复
热议问题