Bootstrap FreeKB - Node.js - Create file using fs
Node.js - Create file using fs

Updated:   |  Node.js articles

fs.writeFile can be used to create (write) a file asynchronously which basically means that other async logic in the script may run before or after fs.writeFile. In this example, sometimes foo.txt would be created first and bar.txt would be created second. Other times, bar.txt would be created first and foo.txt would be created second.

const fs = require("fs")

const foo_file = "/tmp/foo.txt"
const bar_file = "/tmp/bar.txt"

fs.writeFile(foo_file, 'Hello World', (err) => {
  if (err) {
    console.error(err)
  } else {
    console.log(`Successfully created ${foo_file}`)
  }
})

fs.writeFile(bar_file, 'Hello World', (err) => {
  if (err) {
    console.error(err)
  } else {
    console.log(`Successfully created ${bar_file}`)
  }
})

 

Be aware that if you are using a Node.js module instead of CommonJS, you will have "type": "module" in package.json. In this scenario, you will use import instead of require.

import fs from "fs"

 

fs.writeFileSync can be used to create (write) a file synchronously which basically means that the script reads like a book, from the top of the script to the bottom of the script, doing things in the order. In this example, foo.txt would always be created first and bar.txt would be created second.

import fs from "fs"

const foo_file = "/tmp/foo.txt"
const bar_file = "/tmp/bar.txt"

fs.writeFileSync(foo_file, 'Hello World', (err) => {
  if (err) {
    console.error(err)
  } else {
    console.log(`Successfully created ${foo_file}`)
  }
})

fs.writeFileSync(bar_file, 'Hello World', (err) => {
  if (err) {
    console.error(err)
  } else {
    console.log(`Successfully created ${bar_file}`)
  }
})

 

You may want to also include fs.existsSync to determine if the file already exists.

import fs from "fs"

const my_file = "/tmp/example.txt"

if (fs.exists(my_file)) {
  console.warn(`${my_file} already exists`)
} else {
  fs.writeFile(my_file, 'Hello World', err => {
    if (err) {
      console.error(err)
    } else {
      console.log(`Successfully created ${my_file}`)
    }
  })
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter be0a45 in the box below so that we can be sure you are a human.