Using filesystem in node.js with async / await

I would like to use async/await with some filesystem operations. Normally async/await works fine because I use babel-plugin-syntax-async-functions. But with this code I run into the if case where names is undefined: import fs from ‘fs’; async function myF() { let names; try { names = await fs.readdir(‘path/to/dir’); } catch (e) { console.log(‘e’, e); } … Read more

Node.js check if file exists

How do i check the existence of a file? In the documentation for the module fs there’s a description of the method fs.exists(path, callback). But, as I understand, it checks for the existence of only directories. And I need to check the file! How can this be done? 20 Answers 20

How to create full path with node’s fs.mkdirSync?

I’m trying to create a full path if it doesn’t exist. The code looks like this: var fs = require(‘fs’); if (!fs.existsSync(newDest)) fs.mkdirSync(newDest); This code works great as long as there is only one subdirectory (a newDest like ‘dir1’) however when there is a directory path like (‘dir1/dir2’) it fails with Error: ENOENT, no such … Read more

How to append to a file in Node?

I am trying to append a string to a log file. However writeFile will erase the content each time before writing the string. fs.writeFile(‘log.txt’, ‘Hello Node’, function (err) { if (err) throw err; console.log(‘It\’s saved!’); }); // => message.txt erased, contains only ‘Hello Node’ Any idea how to do this the easy way? 18 s … Read more