Writing files in Node.js

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

    fs.createWriteStream(path[,options])

    options may also include a start option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a flags mode of r+ rather than the default mode w. The encoding can be any one of those accepted by Buffer.

    If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.

    Like ReadStream, if fd is specified, WriteStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to net.Socket.

    If options is a string, then it specifies the encoding.

    After, reading this long article. You should understand how it works. So, here's an example of createWriteStream().

    /* The fs.createWriteStream() returns an (WritableStream {aka} internal.Writeable) and we want the encoding as 'utf'-8 */
    /* The WriteableStream has the method write() */
    fs.createWriteStream('out.txt', 'utf-8')
    .write('hello world');
    
    0 讨论(0)
  • 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 } }

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

    The answers provided are dated and a newer way to do this is:

    const fsPromises = require('fs').promises
    await fsPromises.writeFile('/path/to/file.txt', 'data to write')
    

    see documents here for more info

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

    OK, it's quite simple as Node has built-in functionality for this, it's called fs which stands for File System and basically, NodeJS File System module...

    So first require it in your server.js file like this:

    var fs = require('fs');
    

    fs has few methods to do write to file, but my preferred way is using appendFile, this will append the stuff to the file and if the file doesn't exist, will create one, the code could be like below:

    fs.appendFile('myFile.txt', 'Hi Ali!', function (err) {
      if (err) throw err;
      console.log('Thanks, It\'s saved to the file!');
    });
    
    0 讨论(0)
  • 2020-11-21 12:28

    You may write to a file using fs (file system) module.

    Here is an example of how you may do it:

    const fs = require('fs');
    
    const writeToFile = (fileName, callback) => {
      fs.open(fileName, 'wx', (error, fileDescriptor) => {
        if (!error && fileDescriptor) {
          // Do something with the file here ...
          fs.writeFile(fileDescriptor, newData, (error) => {
            if (!error) {
              fs.close(fileDescriptor, (error) => {
                if (!error) {
                  callback(false);
                } else {
                  callback('Error closing the file');
                }
              });
            } else {
              callback('Error writing to new file');
            }
          });
        } else {
          callback('Could not create new file, it may already exists');
        }
      });
    };
    

    You might also want to get rid of this callback-inside-callback code structure by useing Promises and async/await statements. This will make asynchronous code structure much more flat. For doing that there is a handy util.promisify(original) function might be utilized. It allows us to switch from callbacks to promises. Take a look at the example with fs functions below:

    // Dependencies.
    const util = require('util');
    const fs = require('fs');
    
    // Promisify "error-back" functions.
    const fsOpen = util.promisify(fs.open);
    const fsWrite = util.promisify(fs.writeFile);
    const fsClose = util.promisify(fs.close);
    
    // Now we may create 'async' function with 'await's.
    async function doSomethingWithFile(fileName) {
      const fileDescriptor = await fsOpen(fileName, 'wx');
    
      // Do something with the file here...
    
      await fsWrite(fileDescriptor, newData);
      await fsClose(fileDescriptor);
    }
    
    0 讨论(0)
  • 2020-11-21 12:32

    There are a lot of details in the File System API. The most common way is:

    const fs = require('fs');
    
    fs.writeFile("/tmp/test", "Hey there!", function(err) {
        if(err) {
            return console.log(err);
        }
        console.log("The file was saved!");
    }); 
    
    // Or
    fs.writeFileSync('/tmp/test-sync', 'Hey there!');
    
    0 讨论(0)
提交回复
热议问题