Note: All examples here are synchronous for simplicity. You can easily make them asynchronous just by adding 'Async' to method names and expecting promise to be returned instead of ready value.
You can create many fs-jetpack objects with different internal working directories (which are independent of process.cwd()
) and work on directories in a little more object-oriented manner.
const src = jetpack.cwd('path/to/source');
const dest = jetpack.cwd('path/to/destination');
src.copy('foo.txt', dest.path('bar.txt'));
You can write JavaScript object directly to disk and it will be transformed to JSON automatically.
const obj = { greet: "Hello World!" };
jetpack.write('file.json', obj);
Then you can get your object back just by telling read method that it's a JSON.
const obj = jetpack.read('file.json', 'json');
For essential data you might consider "atomic write" feature. To read more about "why" and "how" please see: Transactionally writing files in Node.js Jetpack implements this simple trick and makes it available as an option.
jetpack.write('important_config.json', { atomic: true });
Everyone who did something with files for sure seen "ENOENT, no such file or directory" error. Fs-jetpack tries to recover from it if possible.
- For write/creation operations, if any of parent directories doesn't exist jetpack will just create them as well.
- For read/inspect operations, if file or directory doesn't exist
undefined
is returned instead of throwing.
.
|- greets
|- greet.txt
|- greet.json
|- greets-i18n
|- polish.txt
Peace of cake with jetpack!
jetpack
.dir('greets')
.file('greet.txt', { content: 'Hello world!' })
.file('greet.json', { content: { greet: 'Hello world!' } })
.cwd('..')
.dir('greets-i18n')
.file('polish.txt', { content: 'Witaj świecie!' });
jetpack.find('foo', {
matching: '*.tmp'
})
.forEach(jetpack.remove);
const src = jetpack.cwd('path/to/source');
const dest = jetpack.dir('path/to/destination', { empty: true });
src.copy('.', dest.path(), {
matching: ['./vendor/**', '*.html', '*.png', '*.jpg'],
overwrite: true
});
const config = src.read('config.json', 'json');
config.env = 'production';
dest.write('config.json', config);
const tmp = jetpack.tmpDir();
tmp.append("data.txt", "First chunk of data");
tmp.append("data.txt", "Second chunk of data");
tmp.append("data.txt", "Third chunk of data");
tmp.copy("data.txt", "/some/other/path/data.txt");
tmp.remove();