How to return a promise when writestream finishes?

You’ll want to use the Promise constructor: function writeToFile(filePath: string, arr: string[]): Promise<boolean> { return new Promise((resolve, reject) => { const file = fs.createWriteStream(filePath); for (const row of arr) { file.write(row + “\n”); } file.end(); file.on(“finish”, () => { resolve(true); }); // not sure why you want to pass a boolean file.on(“error”, reject); // don’t … Read more

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

Update NodeJS version 10.12.0 has added a native support for both mkdir and mkdirSync to create a directory recursively with recursive: true option as the following: fs.mkdirSync(targetDir, { recursive: true }); And if you prefer fs Promises API, you can write fs.promises.mkdir(targetDir, { recursive: true }); Original Answer Create directories recursively if they do not … Read more

Get all files recursively in directories NodejS

It looks like the glob npm package would help you. Here is an example of how to use it: File hierarchy: test ├── one.html └── test-nested └── two.html JS code: const glob = require(“glob”); var getDirectories = function (src, callback) { glob(src + ‘/**/*’, callback); }; getDirectories(‘test’, function (err, res) { if (err) { console.log(‘Error’, … Read more

Module not found: Can’t resolve ‘fs’ in Next.js application

If you use fs, be sure it’s only within getInitialProps or getServerSideProps. (anything includes server-side rendering). You may also need to create a next.config.js file with the following content to get the client bundle to build: For webpack4 module.exports = { webpack: (config, { isServer }) => { // Fixes npm packages that depend on … Read more

Node.js check if file exists

Consider opening the file directly, to avoid race conditions: const fs = require(‘fs’); fs.open(‘foo.txt’, ‘r’, function (err, fd) { // … }); Using fs.existsSync: if (fs.existsSync(‘foo.txt’)) { // … } Using fs.stat: fs.stat(‘foo.txt’, function(err, stat) { if (err == null) { console.log(‘File exists’); } else if (err.code === ‘ENOENT’) { // file does not exist … Read more