Writing files in Node.js

前端 未结 19 2031
情歌与酒
情歌与酒 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:09

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

提交回复
热议问题