Writing files in Node.js

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

    Point 1:

    If you want to write something into a file. means: it will remove anything already saved in the file and write the new content. use fs.promises.writeFile()

    Point 2:

    If you want to append something into a file. means: it will not remove anything already saved in the file but append the new item in the file content.then first read the file, and then add the content into the readable value, then write it to the file. so use fs.promises.readFile and fs.promises.writeFile()


    example 1: I want to write a JSON object in my JSON file .

    const fs = require('fs');
    

    writeFile (filename ,writedata) async function writeFile (filename ,writedata) { try { await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8'); return true } catch(err) { return false } }

提交回复
热议问题