Create folder in javascript

How can I create new folder/file with javascript?

I am building an app, and I got to the part where I need to create new folder/file in directory that is in the app. I made forms for those files/folders, and buttons to create them,but I’m not sure how they actually appear. I found thishttp://community.hpe.com/t5/HPE-Service-Manager-Service/Javascript-Create-New-Local-Folder/td-p/6768020, but I am not sure is this what am I searching for.

I’m assuming that you want to create the file/folder (path) on the server of the app? — or is this client side? Which ever it is, both is possible, I just need to know which and I’ll post an answer.

You can use webkitRequestFileSystem at chrome or chromium 13+ and both webkitRequestFileSystem and new File() constructor at versions 38+ see stackoverflow.com/questions/36098129/…

1 Answer 1

Sources

For a JavaScript solution for either client-side or server-side, you can use Node.js; however,

  • client side requires a package called: «NWJS» available here: http://nwjs.io/
  • server side only requires «Node.js» available here: https://nodejs.org

You can find extensive documentation on either of these «JavaScript» solutions; however, there are other «JavaScript» solutions available, NodeJS is very popular.

If you work with another language on the server, like PHP, you can find more info about it here: http://php.net

Solution

The following describes a JavaScript solution with code for server-side that you can just copy & paste and modify to your needs.

This assumes you are running NodeJs on Linux and that the file/folder (path) is not recursive. The example below is not tested, feel free to test & fix as necessary.

Читайте также:  Android new activity kotlin

For the client-side code interacting with the «server-side» example below, create an HTML form that uses: method=»PUT» and the fields as required by the vars ; -OR- use an AJAX method to accomplish the same.

Server-side: NodeJS

let http = require('http'); //File System package. let fsys = require('fs'); let makePath = function(root, path, data) < try < fsys.accessSync(root, fsys.W_OK); >catch(err) < return > path = ((path[0] == '/') ? path.substr(1, path.length) : path); if (path.split('/').length > 2) < return ; > if (fsys.existsSync(path)) < return ; > if (path[path.length -1] == '/') < fsys.mkdirSync(root +'/'+ path.substr(0, path.length -2)); >else < fsys.writeFileSync((root +'/'+ path), (data || ' '), 'utf8'); >return ; >; http.createServer ( function(request, response) < let vars = url.parse(request.url); if (path && (path.indexOf('/') >-1) && (request.method == 'PUT')) < var resp = makePath(__dirname, vars.path, vars.data); response.statusCode = resp.code; response.setHeader('Content-Type', 'text/plain'); response.end(resp.text); >> ).listen(8124); 

Источник

How to create and delete folders and files in JavaScript/ NodeJS

Learn Algorithms and become a National Programmer

In this tutorial at OpenGenus, we will learn how to create or remove/ delete files and directories in Node.JS (JavaScript). We will use the filesystem module (fs) to achieve this.

Accessing file system is a common task but not with Javascript since it was meant to run in a browser. Although Html5 comes with a file system API but it is not fully supported in every browser yet. But installation of nodejs comes with a module which can help us to overcome our problem that is ‘fs’ or filesystem.

FileSystem module

Filesystem or ‘fs’ module acts as a wrapper or container to perform various files operations.Here we will see how to create and delete file/directories in synchronous and asynchrounous modes.You can further read about the module in file system.

How to access ‘fs’ or filesystem module in your program?

To include a module in a program one can use require keyword as shown below:

Читайте также:  Main function in php class

One more thing variable or constant should be of the same name as that of the module.So,with this line of code we can access all the built-in functions in ‘fs’ module.

Create and Delete files in your Javacript/NodeJS program

Since there are two modes synchronous and asynchrounous in which we can create and files so we will see them respectively.

But before that why don’t we learn what do we mean by synchronous and asynchronous mode and it’s impact on the process.

When you execute something or a code synchronously,you wait till it finishes before you go to the next task. When you execute something asynchronously you can move on to the next task before it finishes.

Now, it is basically means it that you can run multiple process at a same time without any problem in asynchronous mode but in synchronous only one process is executed at a time.

Now when we talk about synchronous and asynchronous mode in ‘fs’ module we mean that in synchronous mode first file/folder is created before any other task is executed whereas in asynchronous mode both the process creating of file/ folder or writing data or callback functions can execute simultaneously which we will see further down below.

Synchronous

1.Create a file Synchronously

fs.writeFileSync(file, data[,options]) 
fs.writeFileSync('mytext.txt',"hello world 3000!"); 

Источник

How to create a directory in Node.js

In a Node.js application, you can use the mkdir() method provided by the fs core module to create a new directory. This method works asynchronously to create a new directory at the given location.

Here is an example that demonstrates how you can use the mkdir() method to create a new folder:

const fs = require('fs') // directory path const dir = './views' // create new directory fs.mkdir(dir, err =>  if (err)  throw err > console.log('Directory is created.') >) 

The above code will create a new directory called views in the current directory. However, if the views folder already exists in the current directory, it will throw an error.

To make sure that the directory is only created if it doesn’t already exist, you can use the existsSync() method to check if the given directory exists or not.

Here is an example that checks for the existence of the directory before using the mkdirSync() method to create it:

const fs = require('fs') // directory path const dir = './views' // create new directory try  // first check if the directory already exists if (!fs.existsSync(dir))  fs.mkdirSync(dir) console.log('Directory is created.') > else  console.log('Directory already exists.') > > catch (err)  console.log(err) > 

What if you want to recursively create multiple nested directories that don’t already exist? You can pass an optional boolean parameter called recursive to the mkdir() and mkdirSync() methods to ensure that all parent folders are also created. Let us look at the following example:

const fs = require('fs') // directory full path const dir = './views/includes/layouts' // recursively create multiple directories fs.mkdir(dir,  recursive: true >, err =>  if (err)  throw err > console.log('Directory is created.') >) 

When the recursive parameter is true , the mkdir() method doesn’t throw any error even if the path already exists. So it is safe to use it even when creating a single directory. Read this guide to learn more about reading and writing files in a Node.js application. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Оцените статью