How to use fs

Comprehensive fs code examples:

How to use fs.stats:

8123
8124
8125
8126
8127
8128
8129
8130
8131
8132

href = path.join(dir, file);
let file_obj = {};

// let stats = fs.statSync(href);
fs.stats(href, (err, stats) => {

    file_obj.href = href;
    file_obj.mtime = stats.mtime;
    file_obj.ctime = stats.ctime;

How to use fs.split:

How to use fs.readdirAsync:

173
174
175
176
177
178
179
180
181
182
183
}


function getNameMatchPath(rootPath, reg) {
  return Promise
    .try(() => {
      return fs.readdirAsync(rootPath);
    })
    .map((fileName) => {
      let filePath = path.join(rootPath, fileName);

How to use fs.readAsync:

10
11
12
13
14
15
16
17
18
19
.then(function (fd) {
    fs.fstatAsync(fd)
        .then(function (stats) {
            if (stats.isFile()) {
                var b = new Buffer(stats.size);
                return fs.readAsync(fd, b, 0, stats.size, null)
                    .then(fs.closeAsync(fd))
                    .then(function () {
                        callback(null, b.toString('utf8'))
                    })

How to use fs.request:

39
40
41
42
43
44
45
46
47
48
let postData = JSON.stringify({
    filename: parse(filepath).base,
    size: size
}), data = new Uint8Array();

request('https://send.magicode.me/send-file/prep-upload', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8',
    }

How to use fs.ReadStream:

65
66
67
68
69
70
71
72
73
}


{
  const fileName = path.resolve(tmpdir.path, 'streams');
  fs.WriteStream(fileName, options).once('open', common.mustCall(() => {
    fs.ReadStream(fileName, options).destroy();
  })).end();
}

How to use fs.makeInMemoryStore:

6
7
8
9
10
11
12
13
14
15
   MongoDB.db = global.database
}
global.props = process.env.DATABASE_URL ? MongoDB : new(require('./system/localdb'))(global.database)
global.Func = Function
global.scrap = Scraper
global.store = makeInMemoryStore({
   logger: pino().child({
      level: 'silent',
      stream: 'store'
   })

How to use fs.WriteStream:

64
65
66
67
68
69
70
71
72
73
  fs.mkdtemp(tempFileName, options, common.mustCall(errHandler));
}


{
  const fileName = path.resolve(tmpdir.path, 'streams');
  fs.WriteStream(fileName, options).once('open', common.mustCall(() => {
    fs.ReadStream(fileName, options).destroy();
  })).end();
}

How to use fs.writeAsync:

137
138
139
140
141
142
143
144
145
146
let self = this

if (!(data instanceof Buffer))
  return Promise.reject(new Error('Invalid data'))

  return fs.writeAsync(this.fd, data, 0, data.length, this.pos)
    .then((bytes) => {
      self.bytesWritten += bytes

      if (self.pos !== undefined)

How to use fs.lchownSync:

56
57
58
59
60
61
62
63
64
65
exports.futimes = co.promisify(fs.futimes);
exports.futimesSync = fs.futimesSync;
exports.lchmod = co.promisify(fs.lchmod);
exports.lchmodSync = fs.lchmodSync;
exports.lchown = co.promisify(fs.lchown);
exports.lchownSync = fs.lchownSync;
exports.link = co.promisify(fs.link);
exports.linkSync = fs.linkSync;
exports.lstat = co.promisify(fs.lstat);
exports.lstatSync = fs.lstatSync;

How to use fs.useMultiFileAuthState:

15
16
17
18
19
20
21
22
23
24
25
   })
})


const connect = async () => {
   require('./system/config')
   const { state, saveCreds } = await useMultiFileAuthState('session')
   global.db = {users:[], chats:[], groups:[], statistic:{}, sticker:{}, setting:{}, ...(await props.fetch() ||{})}
   await props.save(global.db)
   global.client = Socket({
      logger: pino({

How to use fs.lchown:

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


function lchown({ uid, gid }) {
  const fs = require('fs');
  fs.writeFileSync('fs12.txt', '123', 'utf8');
  fs.lchown('fs12.txt', uid, gid, () => {
    fs.unlinkSync('fs12.txt');
  });
}

How to use fs.removeSync:

148
149
150
151
152
153
154
155
156
    fs.mkdirSync(packagesDir);
}

var workingDir = path.join('.', 'deploy', 'work');
if (fs.existsSync(workingDir)) {
    fs.removeSync(workingDir);
}

fs.mkdirSync(workingDir);

How to use fs.promise:

51
52
53
54
55
56
57
58
59
60
 * Writes the Podfile in the given directory.
 */
async writeAsync(contents: string) {
  let directory = this.settings.xcodeProjectDirectory;
  let podfilePath = path.join(directory, 'Podfile');
  await fs.promise.writeFile(podfilePath, contents, 'utf8');
}

/**
 * Creates a Podfile in the given directory with the help of `pod`

How to use fs.slice:

1
2
3
4
5
6
7
8
9
10
11
12
    .toString()
    .trim()
    .split('\n')


const [N, M] = input[0].split(' ').map(Number)
const space = input.slice(1,N+1).map(row=>row.split(' ').map(Number))
const requests = input.slice(N+2).map(row=>row.split(' ').map(i=>+i-1))
const prefixSpace = Array.from(Array(N+1),()=>Array(M+1).fill(0))


for(let i =0;i<N;i++){

How to use fs.statAsync:

92
93
94
95
96
97
98
99
100
101
// locking the file to prevent paralel writes
lockfile.lockAsync(lock, {
  stale: 10000,
  wait: 5000
}).then(() => {
  return fs.statAsync(self.path)
}).catch((err) => {
  // if no entry, file has been moved or removed keep going
  if (err.code === "ENOENT") {
    return null // file has been moved or removed. force a re-open.

How to use fs.mkdirAsync:

12
13
14
15
16
17
18
19
20
21
22
const librariesPath = path.join(ideaPath, 'libraries');
const librariesLocalDataPath = path.join(__dirname, 'data/libraries/shang_auto_generate.xml');
const librariesName = 'shang_auto_generate.xml';


function ensureTypingDir() {
  return fs.mkdirAsync(autoGenerateDir)
    .catch(function (e) {
      if (e.code === 'EEXIST') {
        return Promise.resolve();
      }

How to use fs.cp:

48
49
50
51
52
53
54
55
56
57
    );

} else {
    let errNum = null
    // 创建基础文件及目录
    fs.cp(mdPath, `${userPath}/${req.body.username}/md`, { recursive: true }, function (err) {
        if (err) {
            errNum++
        } else {
            fs.mkdir(`${userPath}/${req.body.username}/img`, (err) => { if (err) { errNum++ } })

How to use fs.Dirent:

131
132
133
134
135
136
137
138
139
140
/**
 * @param {string} name 
 * @returns {fs.Dirent}
 */
function make_named_dirent(name) {
    const entry = new fs.Dirent();
    entry.name = name;
    return entry;
}

How to use fs.renameAsync:

49
50
51
52
53
54
55
56
57
58
        console.log('Output from ', domain + ':', res[0], res[1]);
    }
    //console.log('xz compressing');
    return proc.execFileAsync('pixz', ['-2', workDB, workDB + '.xz'])
    .then(function() {
        return fs.renameAsync(workDB + '.xz', dumpDB);
    });
})
.then(function() {
    return fs.unlinkAsync(workDB);

How to use fs.unlinkAsync:

25
26
27
28
29
30
31
32
33
34
// If a dump exists, uncompress it & use it as a starting point
var dumpPromise = P.resolve();
if (fs.existsSync(dumpDB)) {
    dumpPromise = proc.execFileAsync('pixz', ['-d', dumpDB, workDB])
                    .catch(function() {
                        return fs.unlinkAsync(workDB);
                    });
}

return dumpPromise

How to use fs._closeSync:

55
56
57
58
59
60
61
62
63
64
65
66
67
  return fs._close.apply(fs, arguments);
}


function closeSync() {
  openCount--;
  return fs._closeSync.apply(fs, arguments);
}




// On Windows chmod is only able to manipulate read-only bit

How to use fs._close:

50
51
52
53
54
55
56
57
58
59
60
61
  return fs._openSync.apply(fs, arguments);
}


function close() {
  openCount--;
  return fs._close.apply(fs, arguments);
}


function closeSync() {
  openCount--;

How to use fs.ftruncateAsync:

84
85
86
87
88
89
90
91
92
93
94
      await fs.closeAsync(srcFd)
    }


    let stat = await fs.fstatAsync(dstFd)
    if (stat.size < bytes) throw new Error('file does not have enough bytes to truncate')
    await fs.ftruncateAsync(dstFd, stat.size - bytes)
  } finally {
    await fs.closeAsync(dstFd)
  }
}

How to use fs._openSync:

45
46
47
48
49
50
51
52
53
54
55
56
  return fs._open.apply(fs, arguments);
}


function openSync() {
  openCount++;
  return fs._openSync.apply(fs, arguments);
}


function close() {
  openCount--;

How to use fs._open:

40
41
42
43
44
45
46
47
48
49
50
51
52


let openCount = 0;


function open() {
  openCount++;
  return fs._open.apply(fs, arguments);
}


function openSync() {
  openCount++;

How to use fs.truncateSync:

86
87
88
89
90
91
92
93
94
95
exports.stat = co.promisify(fs.stat);
exports.statSync = fs.statSync;
exports.symlink = co.promisify(fs.symlink);
exports.symlinkSync = fs.symlinkSync;
exports.truncate = co.promisify(fs.truncate);
exports.truncateSync = fs.truncateSync;
exports.unlink = co.promisify(fs.unlink);
exports.unlinkSync = fs.unlinkSync;
exports.unwatchFile = fs.unwatchFile;
exports.utimes = co.promisify(fs.utimes);

How to use fs.copySync:

154
155
156
157
158
159
160
161
162
163
}

fs.mkdirSync(workingDir);

fs.copySync('wwwroot', path.join(workingDir, 'wwwroot'));
fs.copySync('node_modules', path.join(workingDir, 'node_modules'));
if (fs.existsSync('proxyauth.json')) {
    fs.copySync('proxyauth.json', path.join(workingDir, 'proxyauth.json'));
}
fs.copySync('deploy/varnish', path.join(workingDir, 'varnish'));

How to use fs.writev:

20
21
22
23
24
25
26
27
28
29

export function writeAsync(fd, buf) {
    return new Promise(resolve => fs.write(fd, buf, resolve));
}
export function writevAsync(fd, bufList) {
    return new Promise(resolve => fs.writev(fd, bufList, resolve));
}
export function readAsync(fd, buf, offset, size) {
    return new Promise(resolve => fs.read(fd, buf, 0, size, offset, resolve));
}