How to use the writeFile function from fs

Find comprehensive JavaScript fs.writeFile code examples handpicked from public code repositorys.

fs.writeFile is a Node.js function that writes data to a file, replacing the file if it already exists.

128
129
130
131
132
133
134
135
136
137
    };
try {
    _writeFile(
        file, content, charset,
        function (file, content) {
            fs.writeFile(file, content, function (err) {
                callback({
                    error: err,
                    file: file
                });
fork icon124
star icon815
watch icon42

+ 30 other calls in file

141
142
143
144
145
146
147
148
149
150
  });
}

async function writeAsync(path, content) {
  return new Promise((resolve, reject) => {
    fs.writeFile(INDEX_PATH, INDEX_CONTENT, 'utf8', err => {
      if (err)
        reject(err);
      else
        resolve();
fork icon69
star icon796
watch icon14

+ 15 other calls in file

How does fs.writeFile work?

fs.writeFile is a Node.js method that writes data to a file, replacing the file if it already exists or creating a new file if it does not. It takes a file path, data to write, and optional encoding and callback function as arguments. The data can be a string, buffer, or typed array. If no encoding is specified, it defaults to 'utf8'. The callback function is called after the file is written, and receives an error argument if there was an error or null if there was no error.

32
33
34
35
36
37
38
39
40
41
* fs.truncate(): 将传递的文件名标识的文件截断为指定的长度。相关方法:fs.ftruncate()。
* fs.unlink(): 删除文件或符号链接。
* fs.unwatchFile(): 停止监视文件上的更改。
* fs.utimes(): 更改文件(通过传入的文件名指定)的时间戳。相关方法:fs.futimes()。
* fs.watchFile(): 开始监视文件上的更改。相关方法:fs.watch()。
* fs.writeFile(): 将数据写入文件。相关方法:fs.write()。

> 注意,上面fs提供的方法都是异步的,所谓异步的意思是,这些方法都提供了回调函数,方便异步触发相应的处理逻辑。

我们举一个简单的读取文件的例子:
fork icon191
star icon570
watch icon16

+ 5 other calls in file

452
453
454
455
456
457
458
459
460
461
    "browser"
  )
) {
  mappingUrl += "?dt=" + new Date().getTime();
}
fs.writeFile(
  outputPath,
  result.code + "\n\n//# sourceMappingURL=" + mappingUrl,
  { encoding: "utf-8" },
  function (err) {
fork icon257
star icon757
watch icon77

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
const fs = require("fs");

// Data to write to file
const data = "Hello, world!";

// Write data to file
fs.writeFile("file.txt", data, (err) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log("Data has been written to file.txt");
});

In this example, we require the fs module and define a string data that we want to write to a file named file.txt. We then call the fs.writeFile method and pass it the file path, the data to write, and a callback function that will be executed when the operation is complete. If an error occurs, we log it to the console, otherwise, we log a success message.

44
45
46
47
48
49
50
51
52
53
var pdfFillForm = require('pdf-fill-form');
var fs = require('fs');

pdfFillForm.write('test.pdf', { "myField": "myField fill value" }, { "save": "pdf", 'cores': 4, 'scale': 0.2, 'antialias': true } )
.then(function(result) {
        fs.writeFile("test123.pdf", result, function(err) {
                if(err) {
                        return console.log(err);
                }
                console.log("The file was saved!");
fork icon43
star icon216
watch icon0

+ 41 other calls in file

8
9
10
11
12
13
14
15
16
17
pdfFormFill.writeAsync('test.pdf', { 'myField1': 'myField1 fill text' }, { 'save': 'imgpdf', 'cores': 8, 'scale': 0.2, 'antialias': true }, function(err, result) {
  if (err) {
      return console.log(err);
  }

  fs.writeFile('test_filled_images.pdf', result, function(err) {
    if (err) {
        return console.log(err);
    }
    console.log('The file was saved!');
fork icon43
star icon216
watch icon14

0
1
2
3
4
5
6
7
8
9
'use strict';
const fs = require('fs'),
        path = require('path'),
        writeAsync = function (name, content) {
                return new Promise((resolve, reject) => {
                        fs.writeFile(name, content, 'utf8', (err, result) => {
                                if (err) {
                                        return reject(err);
                                }
                                resolve(result);
fork icon33
star icon644
watch icon31

+ 15 other calls in file

68
69
70
71
72
73
74
75
76
77
      resolve(data)
    })
  })
const writeAsync = (location) => async (content) =>
  new Promise((resolve, reject) => {
    writeFile(location, content, (err) => {
      if (err) {
        reject(err)
      }
      resolve()
fork icon5
star icon18
watch icon3

+ 19 other calls in file

85
86
87
88
89
90
91
92
93
94
    return fs.writeFileSync(fileName, content);
}

static writeAsync(fileName, content, cb) {
    // content=restoreLineEndings(fileName,content)
    return fs.writeFile(fileName, content, cb);
}

static remove(fileName) {
    try {
fork icon156
star icon0
watch icon32

+ 15 other calls in file

62
63
64
65
66
67
68
69
70
71
var opts = {}
if (options.binary) {
        data = new Uint8Array(data)
}
return new Promise(function (resolve, reject) {
        fs.writeFile(path, data, opts, function (error, buffer) {
                if (error) {
                        reject(error)
                } else {
                        resolve()
fork icon4
star icon19
watch icon7

+ 11 other calls in file

60
61
62
63
64
65
66
67
68
69
 * @param {string} content 
 * 
 * @returns {Promise}
 */
const writeFileAsync = (path, content) => new Promise((resolve, reject) => {
    return fs.writeFile(path, content, (err) => err ? reject(err) : resolve())
});

/**
 * Directories to ignore
fork icon7
star icon10
watch icon3

+ 3 other calls in file

74
75
76
77
78
79
80
81
82
83
84
  assert.equal(success, 2);
  console.log('ok');
});


function testTruncate(cb) {
  fs.writeFile(filename, data, function(er) {
    if (er) return cb(er);
    fs.stat(filename, function(er, stat) {
      if (er) return cb(er);
      assert.equal(stat.size, 1024 * 16);
fork icon9
star icon15
watch icon0

42
43
44
45
46
47
48
49
50
51
52
53
}


function saveStats() {
    stats.lastupdatetime = Date().toString();
    var save = JSON.stringify(stats)
    fs.writeFile("assets/stats.txt", save);
    console.log("Stats SAVED as " + stats.lastupdatetime)
}


// END of STATISTICSjs
fork icon0
star icon2
watch icon0

+ 3 other calls in file

181
182
183
184
185
186
187
188
189
190

static writeYaml(filename, obj, cb) {
  // Write yaml version of an object to a file
  try {
    const y = yaml.dump(obj);
    fs.writeFile(filename, y, { encoding: 'utf8' }, (err) => {
      if (err) { debug('Unable to write yaml to %s: %s', filename, err.message); }
      cb(err);
    });
  } catch (err) { // Typically a yaml dump error
fork icon20
star icon211
watch icon20

360
361
362
363
364
365
366
367
368
369
370
371
      config.submissionEndpoint = ep[i].protocol + '://' +
        fu.hostname + ':' + ep[i].port + '/post';
    }


    var text = JSON.stringify(config, null, 2);
    fs.writeFile(configFile, text, callback);
  });
}


function loadConfig(callback) {
fork icon14
star icon8
watch icon15

+ 3 other calls in file

185
186
187
188
189
190
191
192
193
194
195
196
197


        console.log(dataByTypeAndDomain);
    })
    // organize by domain too...


    fs.writeFile(output_path, JSON.stringify(data),
        () => console.log("done!"));
}


console.log(process.cwd())
fork icon6
star icon60
watch icon6

109
110
111
112
113
114
115
116
117
118
	}
    }
}
if (boolneedUpdate) {
    var str = JSON.stringify(TempShareCache, null, 2);
    fs.writeFile(strShare, str, function (err) {
        if (err) {
            console.log(err);
            console.log("\n【缓存文件Fruit_ShareCache.json更新失败!】\n");
        } else {
fork icon4
star icon12
watch icon2

793
794
795
796
797
798
799
800
801
802
    console.error(error);
}

if (boolneedUpdate) {
    var str = JSON.stringify(TempCK, null, 2);
    fs.writeFile(strCKFile, str, function (err) {
        if (err) {
            console.log(err);
            console.log("更新CKName_cache.json失败!");
        } else {
fork icon2
star icon3
watch icon1

131
132
133
134
135
136
137
138
139
140
};

loop(0)
  .then(function() {
    csv = data2CSV(data);
    fs.writeFile(outputFileName, csv.join('\r\n'), function(err) {
      if (err) throw err;
      console.log('File saved. ' + outputFileName);
    });
  });
fork icon3
star icon2
watch icon3

298
299
300
301
302
303
304
305
306
307
//console.log(request.body.chat);
//var bg = "body {background-image: linear-gradient(rgba(19,21,44,0.75), rgba(19,21,44,0.75)), url(../backgrounds/"+request.body.bg+");}";
var dir_name = String(request.body.avatar_url).replace(`.${characterFormat}`,'');
let chat_data = request.body.chat;
let jsonlData = chat_data.map(JSON.stringify).join('\n');
fs.writeFile(chatsPath+dir_name+"/"+request.body.file_name+'.jsonl', jsonlData, 'utf8', function(err) {
    if(err) {
        response.send(err);
        return console.log(err);
        //response.send(err);
fork icon60
star icon276
watch icon17

+ 5 other calls in file