Changeset View
Changeset View
Standalone View
Standalone View
lib/s.js
- This file was added.
const fs = require('fs'); | |||||
const path = require('path'); | |||||
const util = require('util'); | |||||
const access = util.promisify(fs.access); | |||||
const writeFile = util.promisify(fs.writeFile); | |||||
const md5 = require('md5'); | |||||
const makeDir = require('make-dir'); | |||||
class S { | |||||
constructor({ output_dir, path_prefix }) { | |||||
this.output_dir = output_dir; | |||||
this.path_prefix = path_prefix; // for example: "/previews/92180392ueu093" | |||||
} | |||||
async addOutputFile({ output_subdir, base_name, generator, deps }) { | |||||
const hash = md5(JSON.stringify(deps)); | |||||
let output_filename = base_name.split('.'); | |||||
output_filename.splice(output_filename.length - 1, 0, hash); | |||||
output_filename = output_filename.join('.'); | |||||
if (output_subdir[0] === '/') { | |||||
output_subdir = '.' + output_subdir; | |||||
} | |||||
const output_path = path.resolve( | |||||
this.output_dir, | |||||
output_subdir, | |||||
output_filename | |||||
); | |||||
try { | |||||
await access(path.resolve(output_path, '..')); | |||||
} catch (error) { | |||||
if (error.code === 'ENOENT') { | |||||
arkadiusz-wieczorek: Ten kod błędu oznacza `ENOENT: 2 - No such file or directory` więc może lepiej zmienić… | |||||
await makeDir(path.resolve(output_path, '..')); | |||||
} else throw error; | |||||
} | |||||
try { | |||||
await access(output_path); | |||||
} catch (error) { | |||||
await writeFile(output_path, await generator()); | |||||
} | |||||
return path.join(this.path_prefix, output_subdir, output_filename); | |||||
} | |||||
node_require(module_name) { | |||||
Done Inline ActionsTak jak wspomniałem wcześniej może lepiej użyć node_require? arkadiusz-wieczorek: Tak jak wspomniałem wcześniej może lepiej użyć `node_require`? | |||||
try { | |||||
return require(module_name); | |||||
} catch (e) { | |||||
console.error(e); | |||||
throw new Error( | |||||
`Could not resolve module '${module_name}'. It might not be installed or you're running the s.node_require function in the browser, while it's only supposed to be called on backend side` | |||||
); | |||||
} | |||||
} | |||||
} | |||||
module.exports = S; |
Ten kod błędu oznacza ENOENT: 2 - No such file or directory więc może lepiej zmienić fileExists na access lub exists