How to use the access function from fs
Find comprehensive JavaScript fs.access code examples handpicked from public code repositorys.
fs.access is a Node.js method used to check the accessibility of a file system path.
7 8 9 10 11 12 13 14 15 16
nodejs中有一个非常重要的模块叫做fs。这个模块提供了许多非常实用的函数来访问文件系统并与文件系统进行交互。 简单统计一下,fs提供了下面这么多种使用的文件操作方法: * fs.access(): 检查文件是否存在,以及 Node.js 是否有权限访问。 * fs.appendFile(): 追加数据到文件。如果文件不存在,则创建文件。 * fs.chmod(): 更改文件(通过传入的文件名指定)的权限。相关方法:fs.lchmod()、fs.fchmod()。 * fs.chown(): 更改文件(通过传入的文件名指 定)的所有者和群组。相关方法:fs.fchown()、fs.lchown()。 * fs.close(): 关闭文件描述符。
+ 5 other calls in file
GitHub: TavernAI/TavernAI
139 140 141 142 143 144 145 146 147 148 149
app.use((req, res, next) => { if (req.url.startsWith('/characters/') && is_colab && process.env.googledrive == 2) { const filePath = path.join(charactersPath, decodeURIComponent(req.url.substr('/characters'.length))); fs.access(filePath, fs.constants.R_OK, (err) => { if (!err) { res.sendFile(filePath); } else { res.send('Character not found: '+filePath);
How does fs.access work?
fs.access is a method provided by Node.js that is used to check the accessibility of a file system path. The method takes two arguments: the first is the path to the file or directory to check, and the second is an optional mode parameter that specifies the type of accessibility check to perform. If the mode argument is not provided, fs.access will check if the file or directory exists and the Node.js process has permission to access it. If the file or directory does not exist or the process does not have permission to access it, fs.access will return an error. If the mode argument is provided, fs.access will perform a more specific check. The mode argument can be set to one of the following constants: fs.constants.F_OK: This constant checks if the file or directory exists. fs.constants.R_OK: This constant checks if the file or directory is readable. fs.constants.W_OK: This constant checks if the file or directory is writable. fs.constants.X_OK: This constant checks if the file or directory is executable. If fs.access is called with a mode argument, it will return an error if the file or directory does not exist, or if the specified access mode is not available for the file or directory. In summary, fs.access is a method in Node.js that allows you to check whether a file or directory exists and whether the current process has permission to read, write, or execute it.
316 317 318 319 320 321 322 323 324 325
Object.keys(config.availableLanguageAssets).forEach(langKey => { toBeEvaluated.push(Validator.customEvaluationAsync(async () => { const langFilePath = path.join(languageDirPath, `${langKey}.json`); try { await fs.access(langFilePath, fsConstants.F_OK); return true; } catch(e) { return false }
GitHub: alancnet/await-file
25 26 27 28 29 30 31 32 33 34
* @returns Returns `true` if the file is accessible or `false` if the file is inaccessible. * * @example * The following example checks if the file `/etc/passwd` can be read and written by the current process. * ```js * await fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK); * ``` * * Note: Using `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. * Doing so introduces a race condition, since other processes may change the file's state between the two calls.
+ 11 other calls in file
Ai Example
1 2 3 4 5 6 7 8 9 10 11
const fs = require("fs"); const filename = "/path/to/my/file.txt"; fs.access(filename, fs.constants.R_OK, (err) => { if (err) { console.error("Cannot read file: ", err); } else { console.log("File is readable"); } });
In this example, the fs.access() function is used to check if the file located at the specified path (filename) is readable. The second argument (fs.constants.R_OK) is a flag indicating that the function should check for read access. If the file is readable, the callback function is called with no error. If the file is not readable (e.g., it does not exist or the user does not have permission to read it), the callback function is called with an error object.
GitHub: RyderL/Wargame-RCON
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
} const tail = async function(type, host) { let filename = `${config.hosts[host]}/${type == "log" ? "serverlog.txt" : "chat.log"}`; fs.access(filename, fs.constants.F_OK, async (err) => { if(!err) { global[type].tail[host] = new Tail(filename); global[type].tail[host].on("line", async (data) => {
+ 2 other calls in file
229 230 231 232 233 234 235 236 237
res.write(req.url); if(req.url == "/") fs.readFile(__dirname + "/pages/index.html").then(contents => res.end(contents)); else { //We use .then() and .catch() b/c fs.promises is async. fs.access(__dirname + "/pages" + req.url + ".html", fsc.F_OK) .then(() => fs.readFile(__dirname + "/pages" + req.url + ".html").then(contents => res.end(contents))) .catch(() => fs.readFile(__dirname + "/pages/404.html").then(contents => res.end(contents))); }
+ 2 other calls in file
GitHub: cmdwm/0tr.me
124 125 126 127 128 129 130 131 132 133 134
app.get('/i/:file', function(req, res) { const filePath = __dirname + '/uploads/' + req.params.file; // Check if file exists fs.access(filePath, fs.constants.F_OK, function(err) { if (err) { console.error(err); res.redirect('/'); } else {
20 21 22 23 24 25 26 27 28 29
console.log("Error", err) } } else{ let path = `public${process.env.MY_STATIC_FILES_URL}${filename}`; fs.access(path, fs.F_OK, (err) => { if(err){ console.error(err); return; }
665 666 667 668 669 670 671 672 673 674
async loadConfig() { try { console.log("[*] Loading version configuration from a file."); const configPath = `./configs/${this.data_owner}.${this.data_repo}.${this.data_version}.json`; await fs.access(configPath, fsConstants.R_OK); const configContent = await fs.readFile(configPath); this.config = JSON.parse(configContent); this.first_commit = this.config.from_ref;
687 688 689 690 691 692 693 694 695 696 697
}); } function generateMonolingualSubtitle(blocks, targetFile, videoid) { console.log('start generating final subtitle file...' + targetFile); fs.access(targetFile, (err) => { if (!err) { console.log('file exists, remove it'); fs.unlinkSync(targetFile); }
+ 4 other calls in file
514 515 516 517 518 519 520 521 522 523
} const fileData = req.files.file.data; const filename = req.files.file.name; const newFileName = filename.replace(/\s/g, '_'); const filePath = process.cwd() + '/tmp/' + newFileName; // Set the file path fs.access(filePath, fs.constants.F_OK, (err) => { if (!err) { // File already exists, delete it before overwriting fs.unlink(filePath, (err) => { if (err) {
GitHub: fxxkjs/webnoteServer
205 206 207 208 209 210 211 212 213 214
router.post('/addMd', function (req, res) { if (!AES.get(req.cookies.webnote)) { res.send({ code: 0, msg: `非法操作` }) } let path = `${userPath}/${AES.get(req.cookies.webnote)}/md/${req.body.topNavType}/${req.body.leftNavType}/${req.body.mdName}.md` fs.access(path, fs.constants.F_OK, (err) => { if (err) { fs.writeFile(path, "", (err) => { if (err) { res.send({ code: 0, msg: `${req.body.mdName} 创建失败,请稍后重试` })
+ 4 other calls in file
GitHub: khrome/mangrove-json
24 25 26 27 28 29 30 31 32 33
var url = path.join(this.root, name+(this.filetype?'.'+this.filetype:'')); if(url.indexOf('://') !== -1){ stream = request({url: url}); JSONStreamBuild(stream, handler, cb); }else{ fs.access(url, (err) => { if(err) fs.writeFileSync(url, '[]'); stream = fs.createReadStream(url); JSONStreamBuild(stream, handler, cb); });
527 528 529 530 531 532 533 534 535 536
} const fileData = req.files.file.data; const filename = req.files.file.name; const newFileName = filename.replace(/\s/g, '_'); const filePath = process.cwd() + '/tmp/' + newFileName; // Set the file path fs.access(filePath, fs.constants.F_OK, async (err) => { if (!err) { // File already exists, delete it before overwriting fs.unlink(filePath, async (err) => { if (err) {
60 61 62 63 64 65 66 67 68 69
const timer = setTimeout(() => { watcher.close(); reject(new Error(' [checkFileExists] File does not exist, and was not created during the timeout delay.')); }, timeout); fs.access(filePath, fs.constants.R_OK, err => { if (!err) { clearTimeout(timer); watcher.close(); resolve();
20 21 22 23 24 25 26 27 28 29 30
} function access() { const fs = require('fs'); fs.writeFileSync('fs0.txt', '123', 'utf8'); fs.access('fs0.txt', () => { fs.unlinkSync('fs0.txt'); }); }
+ 2 other calls in file
83 84 85 86 87 88 89 90 91 92 93
} // fs.access { assert.throws(() => { fs.access(blockedFile, fs.constants.R_OK, () => {}); }, common.expectsError({ code: 'ERR_ACCESS_DENIED', permission: 'FileSystemRead', resource: path.toNamespacedPath(blockedFile),
+ 7 other calls in file
GitHub: a-labo/asfs
108 109 110 111 112 113 114 115 116 117
* @param {string} filename * @returns {Promise<*>} */ async canWriteAsync(filename) { return new Promise((resolve, reject) => { fs.access(filename, fs.constants.W_OK, (err) => { resolve(!err) }) }) },
+ 3 other calls in file
6 7 8 9 10 11 12 13 14 15
const storedDBName = '/backup/db.sqlite'; const currentDBName = '/sqlite.db'; const tempDBName = '/backup/sqlite.db'; // Check if secondary database exists in storage fs.access(config.root + storedDBName, fs.F_OK, (err) => { if (err) { console.log(err); return false; }
+ 3 other calls in file
fs.readFileSync is the most popular function in fs (2736 examples)