Skip to content

Commit

Permalink
fix(Standalone): Workaround pkg #420 bug
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Jan 3, 2020
1 parent 4b5f531 commit c94a614
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 7 deletions.
15 changes: 8 additions & 7 deletions bin/serverless.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

'use strict';

if (
process.argv[2] === 'binary-postinstall' &&
process.argv.length === 3 &&
require('../lib/utils/isStandaloneExecutable')
) {
require('../scripts/postinstall');
return;
const isStandaloneExecutable = require('../lib/utils/isStandaloneExecutable');

if (isStandaloneExecutable) {
require('../lib/utils/standalone-patch');
if (process.argv[2] === 'binary-postinstall' && process.argv.length === 3) {
require('../scripts/postinstall');
return;
}
}

// global graceful-fs patch
Expand Down
74 changes: 74 additions & 0 deletions lib/utils/standalone-patch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
'use strict';

// Workaround 'pkg' bug: https://github.com/zeit/pkg/issues/420
// Copying files from snapshot via `fs.copyFileSync` crashes with ENOENT
// Overriding copyFileSync with primitive alternative

const fs = require('fs');

if (!fs.copyFile) return;

const path = require('path');

const originalCopyFile = fs.copyFile;
const originalCopyFileSync = fs.copyFileSync;

fs.copyFile = function copyFile(src, dest, flags, callback) {
if (!path.resolve(src).startsWith('/snapshot/')) {
originalCopyFile(src, dest, flags, callback);
return;
}
if (typeof flags === 'function') {
callback = flags;
flags = 0;
} else if (typeof callback !== 'function') {
throw new TypeError('Callback must be a function');
}

fs.readFile(src, (readError, content) => {
if (readError) {
callback(readError);
return;
}
if (flags & fs.constants.COPYFILE_EXCL) {
fs.stat(dest, statError => {
if (!statError) {
callback(Object.assign(new Error('File already exists'), { code: 'EEXIST' }));
return;
}
if (statError.code !== 'ENOENT') {
callback(statError);
return;
}
fs.writeFile(dest, content, callback);
});
} else {
fs.writeFile(dest, content, callback);
}
});
};

fs.copyFileSync = function copyFileSync(src, dest, flags) {
if (!path.resolve(src).startsWith('/snapshot/')) {
originalCopyFileSync(src, dest, flags);
return;
}
const content = fs.readFileSync(src);
if (flags & fs.constants.COPYFILE_EXCL) {
try {
fs.statSync(dest);
} catch (statError) {
if (statError.code !== 'ENOENT') throw statError;
fs.writeFileSync(dest, content);
return;
}
throw Object.assign(new Error('File already exists'), { code: 'EEXIST' });
}
fs.writeFileSync(dest, content);
};

if (!fs.promises) return;

const { promisify } = require('util');

fs.promises.copyFile = promisify(fs.copyFile);

0 comments on commit c94a614

Please sign in to comment.