Read/write files within a Linux kernel module

You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go “one level deeper” and call VFS level functions instead of the syscall handler directly: Includes: #include <linux/fs.h> #include <asm/segment.h> #include <asm/uaccess.h> #include <linux/buffer_head.h> Opening a file (similar to open): struct file *file_open(const char … Read more

fs.writeFile in a promise, asynchronous-synchronous stuff

As of 2019… …the correct answer is to use async/await with the native fs promises module included in node. Upgrade to Node.js 10 or 11 (already supported by major cloud providers) and do this: const fs = require(‘fs’).promises; // This must run inside a function marked `async`: const file = await fs.readFile(‘filename.txt’, ‘utf8’); await fs.writeFile(‘filename.txt’, … Read more

Append to a file in Go

This answers works in Go1: f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) if err != nil { panic(err) } defer f.Close() if _, err = f.WriteString(text); err != nil { panic(err) }

How to write file if parent folder doesn’t exist?

As of Node v10, this is built into the fs.mkdir function, which we can use in combination with path.dirname: var fs = require(‘fs’); var getDirName = require(‘path’).dirname; function writeFile(path, contents, cb) { fs.mkdir(getDirName(path), { recursive: true}, function (err) { if (err) return cb(err); fs.writeFile(path, contents, cb); }); } For older versions, you can use mkdirp: … Read more

Is file append atomic in UNIX?

A write that’s under the size of ‘PIPE_BUF’ is supposed to be atomic. That should be at least 512 bytes, though it could easily be larger (linux seems to have it set to 4096). This assume that you’re talking all fully POSIX-compliant components. For instance, this isn’t true on NFS. But assuming you write to … Read more