Ошибка при создании параллельной задачи Gulp для просмотра и построения пользовательского интерфейса и сервера - PullRequest
0 голосов
/ 02 июля 2019

Я хочу создать проект, который включает в себя и сервер, и код пользовательского интерфейса в одном и том же репозитории, сервер создан с использованием node.js и express, пользовательский интерфейс выполнен с угловым, сервер был создан для обслуживания пользовательского интерфейса и обеспечения API.

Так что я хочу иметь возможность редактировать и компилировать оба кода при изменении кода каждого, для этого я прибег к использованию Gulp.

Вот что я придумал:

Сервер index.js

const express = require('express');
const app = express();
const path = require('path');
const allowedExt = [
    '.js',
    '.ico',
    '.css',
    '.png',
    '.jpg',
    '.woff2',
    '.woff',
    '.ttf',
    '.svg',
];

app.get('/api', (req, res) => {
    res.json({ mark: 52, name: "David", weapon: 'sling' });
});

/**
 * expoe the Angular UI built files
 */
app.get('*', (req, res) => {
    if (allowedExt.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
        res.sendFile(path.resolve(`ui/dist/ui/${req.url}`));
    } else {
        res.sendFile(path.resolve('ui/dist/ui/index.html'));
    }
});

// run the server
app.listen(8000, () => {
    console.log('Example app listening on port 8000!')
});

Файл глотка:

const exec = require('child_process').exec;
const path = require('path');
const { watch, parallel } = require('gulp');
const nodemon = require('gulp-nodemon');


/**
 *  Build the UI 
 */
function ngBuild(done) {
    exec('ng build', (err, stdout, stderr) => {
        if (!err) {
            console.log('UI was built successfully');
        } else {
            console.log('UI build failed with error:');
            console.log(`\n Failed with code ${err.code}\n`);
            done(err.stack);
        }
        done();
    });
}

/**
 * Watch changes in the UI files and build ui
 */
async function UiWatcher() {
    console.log('UI watcher is on');

    process.chdir(path.resolve('ui'));
    watch('src/**/*.*', { delay: 500, queue: false }, ngBuild);
}

/**
 * watch the server code using nodemon
 */
async function server(done) {
        var stream = nodemon({
            script: 'index.js'
            , ext: 'html js'
            , ignore: ['ignored.js']
            , done: done
        });

        stream
            .on('restart', function () {
                console.log('restarted!')
            })
            .on('crash', function () {
                console.error('Application has crashed!\n')
                stream.emit('restart', 10)  // restart the server in 10 seconds
            });
}

exports.default = ngBuild;
exports.watch = UiWatcher;
exports.server = server;
exports.full = parallel(UiWatcher, server);

но когда я запускаю gulp full , он не работает, наблюдатель пользовательского интерфейса работает, но nodemon не работает, когда я запускаю каждый из них, они работают отлично, я получаю следующую ошибку:

[09:44:21] Using gulpfile ~\Documents\personal\node-serve-angular\gulpfile.js
[09:44:21] Starting 'full'...
[09:44:21] Starting 'UiWatcher'...
[09:44:21] Starting 'server'...
UI watcher is on
[09:44:21] Finished 'UiWatcher' after 18 ms
[09:44:21] Finished 'server' after 19 ms
[09:44:21] Finished 'full' after 23 ms
[09:44:31] [nodemon] 1.19.1
[09:44:31] [nodemon] to restart at any time, enter `rs`
[09:44:31] [nodemon] watching: *.*
[09:44:31] [nodemon] starting `node index.js`
\internal/modules/cjs/loader.js:583
    throw err;
    ^

Error: Cannot find module 'C:\Users\DELL\Documents\personal\node-serve-angular\ui\index.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
Application has crashed!

restarted!
[09:44:32] [nodemon] app crashed - waiting for file changes before starting...
...