Writing files in Node.js

前端 未结 19 2051
情歌与酒
情歌与酒 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'.

    0 讨论(0)
  • 2020-11-21 12:06

    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  ('./my_data.json' , {id:1, name:'my name'} )
    async function writeFile  (filename ,writedata) {
        try {
            await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
           console.log ('data is written successfully in the file')
        }
        catch(err) {
            console.log ('not able to write data in the file ')
        }
    }
    

    example2 : if you want to append data to a JSON file. you want to add data {id:1, name:'my name'} to file my_data.json on the same folder root. just call append_data (file_path , data ) function.

    It will append data in the JSON file if the file existed . or it will create the file and add the data to it.

       const fs = require('fs');
       data = {id:1, name:'my name'}
       file_path = './my_data.json'
       append_data (file_path , data )
    
       async function append_data (filename , data ) {
    
          if (fs.existsSync(filename)) {
             read_data = await readFile(filename)
             if (read_data == false) {
                 console.log('not able to read file')
             }
             else {
                 read_data.push(data)
                 dataWrittenStatus = await writeFile(filename, read_data)
                 if dataWrittenStatus == true {
                   console.log('data added successfully')
                 }
                else{
                   console.log('data adding failed')
                }
            }
           else{
              dataWrittenStatus = await writeFile(filename, [data])
              if dataWrittenStatus == true {
                 console.log('data added successfully')
              }
              else{
                 console.log('data adding failed')
              }
          }
       }
    
    
    
    async function readFile  (filePath) {
      try {
        const data = await fs.promises.readFile(filePath, 'utf8')
        return JSON.parse(data)
      }
     catch(err) {
         return false;
      }
    }
    
    async function writeFile  (filename ,writedata) {
      try {
          await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
          return true
      }
      catch(err) {
          return false
      }
    }
    
    0 讨论(0)
  • 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');
            })
        });
    });
    
    0 讨论(0)
  • 2020-11-21 12:10

    Synchronous Write

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

    fs = require('fs');
    
    fs.writeFileSync("foo.txt", "bar");
    

    Asynchronous Write

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

    fs = require('fs');
    
    fs.writeFile('foo.txt', 'bar', (err) => { if (err) throw err; });
    

    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.

    Update: async/await

    fs = require('fs');
    util = require('util');
    writeFile = util.promisify(fs.writeFile);
    
    fn = async () => { await writeFile('foo.txt', 'bar'); }
    
    fn()
    
    0 讨论(0)
  • 2020-11-21 12:10

    You can write to files with streams.

    Just do it like this:

    const fs = require('fs');
    
    const stream = fs.createWriteStream('./test.txt');
    stream.write("Example text");
    
    0 讨论(0)
  • 2020-11-21 12:11

    You can write in a file by the following code example:

    var data = [{ 'test': '123', 'test2': 'Lorem Ipsem ' }];
    fs.open(datapath + '/data/topplayers.json', 'wx', function (error, fileDescriptor) {
      if (!error && fileDescriptor) {
        var stringData = JSON.stringify(data);
        fs.writeFile(fileDescriptor, stringData, function (error) {
          if (!error) {
            fs.close(fileDescriptor, function (error) {
              if (!error) {
                callback(false);
              } else {
                callback('Error in close file');
              }
            });
          } else {
            callback('Error in writing file.');
          }
        });
      }
    });
    
    0 讨论(0)
提交回复
热议问题