node.js : file upload via express and multer

Form-based File Upload in HTML

https://tools.ietf.org/html/rfc1867

Express

Fast, unopinionated, minimalist web framework for node.

Multer

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
NOTE: Multer will not process any form which is not multipart (multipart/form-data).

Client Codes(index.html)

<script type="text/javascript">
function upload(postUrl, fieldName, files)
{
  var formData = new FormData();
  formData.append(fieldName, files);

  var req = new XMLHttpRequest();
  req.open("POST", postUrl);
  req.onload = function(event) { console.log(event.target.responseText); };
  req.send(formData);
}
function onchange() {
  for (let i = 0; i < this.files.length; i++) {
    upload('/uploads', 'uploadfile', this.files[i]);
  }
}
window.onload = function () {
var  input = document.getElementById('file');
input.addEventListener('change', onchange);
}
</script>
<input type="file" id="file" name="file" multiple onchange="upload" />

Server Codes

var express = require('express')
var app = express()
var path = require('path')
var tmpdir = require('os').tmpdir
var upload = require('multer')({dest: tmpdir()})

app.get('/', function (req, res) {
  var indexhtml = 'index.html';
  var tmp = path.resolve(indexhtml);
  res.sendFile(tmp);
})

app.post('/uploads', upload.single('uploadfile'), function (req, res, next) {
  var rp = {'file':req.file, 'body' : req.body, 'ip':req.ip};
  res.send(rp);
})

app.listen(3000)

Run express Server

node index.js

Test

upload
As you can see in the console, the file was uploaded to server and saved with file name of "/tmp/e2f2d3ae260814fc4b589a13d5981aec".

Print all combination of that select n elements from 1,2,3,...,m.

"C" is for "combination". A combination is an un-ordered collection of distinct elements, usually of a prescribed size and taken from a given set.

   C(n, r) = n!/[r!(n-r)!] 
 
#include <stdio.h>
#include <sys/time.h>

int a[1001];

// selected n numbers stored in array a
// a[1], a[2], ... , a[n]
// a[i+1] > a[i]
// a[i] - i <= m - n + 1

void comos(int n, int m) {
  int i,j;
  if (n > m)
    return;
  for (i = 1; i <= n; i++) {
    a[i] = i;
  }
  int cur = n;
  do {
    if (a[cur]-cur <= m - n) {
      for (i = 1; i <= n; i++)
        printf("%d ", a[i]);
      printf("\n");
      a[cur]++;
      continue;
    } else {
      if (cur == 1) {
        break;
      }
      a[--cur]++;
      for (i = 1; i <= (n-cur); i++)
        a[cur+i] = a[cur] + i;
      if (a[cur] - cur < m - n + 1)
        cur=n;
    }
  } while(1);
}

int main() {
  int N, M;
  while (scanf("%d %d", &N, &M) != EOF) {
    if (N <= M) {
      struct timeval begin, end;
      gettimeofday(&begin, 0);
      comos(N, M);
      gettimeofday(&end, 0);
      printf("print comos(%d, %d) used %ld microseconds\n", N, M, end.tv_usec-begin.tv_usec);
    } else {
      printf("Invalid Input, %d <= %d is false\n", N, M);
    }
  }
  return 0;
}
 
1 5
1
2
3
4
5
print comos(1, 5) used 116 microseconds
2 5
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
print comos(2, 5) used 171 microseconds
3 5
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
print comos(3, 5) used 153 microseconds
4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5
print comos(4, 5) used 97 microseconds
5 5
1 2 3 4 5
print comos(5, 5) used 33 microseconds

all learning is understanding relationships

James Comer says that no significant learning can occur without a significant relationship.
George Washington Carver says all learning is understanding relationships.

"You were chosen to be in my class because I am the best teacher and you are the best students, they put us all together so we could show everybody else how to do it."

"Really?"

"Really. We have to show the other classes how to do it, so when we walk down the hall, people will notice us, so you can't make noise. You just have to strut."

"I am somebody. I was somebody when I came. I'll be a better somebody when I leave. I am powerful, and I am strong. I deserve the education that I get here. I have things to do, people to impress, and places to go."

"Yeah!"

You say it long enough, it starts to be a part of you.

PulseAudio example

PulseAudio APIs

pa_simple_new
pa_simple_write
pa_simple_drain
pa_simple_free
https://freedesktop.org/software/pulseaudio/doxygen/examples.html

build command

gcc -o pulse pulse.c `pkg-config --cflags --libs libpulse-simple`

source

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <pulse/simple.h>
#include <pulse/error.h>
#define BUFSIZE 1024
int main(int argc, char* argv[]) {
  /* The Sample format to use */
  static const pa_sample_spec ss = {
      .format = PA_SAMPLE_S16LE, .rate = 44100, .channels = 2};
  pa_simple* s = NULL;
  int ret = 1;
  int error;
  /* replace STDIN with the specified file if needed */
  if (argc > 1) {
    int fd;
    if ((fd = open(argv[1], O_RDONLY)) < 0) {
      fprintf(stderr, __FILE__ ": open() failed: %s\n", strerror(errno));
      goto finish;
    }
    if (dup2(fd, STDIN_FILENO) < 0) {
      fprintf(stderr, __FILE__ ": dup2() failed: %s\n", strerror(errno));
      goto finish;
    }
    close(fd);
  }
  /* Create a new playback stream */
  if (!(s = pa_simple_new(NULL, argv[0], PA_STREAM_PLAYBACK, NULL, "playback",
                          &ss, NULL, NULL, &error))) {
    fprintf(stderr, __FILE__ ": pa_simple_new() failed: %s\n",
            pa_strerror(error));
    goto finish;
  }
  for (;;) {
    uint8_t buf[BUFSIZE];
    ssize_t r;
#if 0
        pa_usec_t latency;
        if ((latency = pa_simple_get_latency(s, &error)) == (pa_usec_t) -1) {
            fprintf(stderr, __FILE__": pa_simple_get_latency() failed: %s\n", pa_strerror(error));
            goto finish;
        }
        fprintf(stderr, "%0.0f usec    \r", (float)latency);
#endif
    /* Read some data ... */
    if ((r = read(STDIN_FILENO, buf, sizeof(buf))) <= 0) {
      if (r == 0) /* EOF */
        break;
      fprintf(stderr, __FILE__ ": read() failed: %s\n", strerror(errno));
      goto finish;
    }
    /* ... and play it */
    if (pa_simple_write(s, buf, (size_t)r, &error) < 0) {
      fprintf(stderr, __FILE__ ": pa_simple_write() failed: %s\n",
              pa_strerror(error));
      goto finish;
    }
  }
  /* Make sure that every single sample was played */
  if (pa_simple_drain(s, &error) < 0) {
    fprintf(stderr, __FILE__ ": pa_simple_drain() failed: %s\n",
            pa_strerror(error));
    goto finish;
  }
  ret = 0;
finish:
  if (s)
    pa_simple_free(s);
  return ret;
}

 

alsa programing example

alsa APIs

snd_pcm_open
snd_pcm_hw_params_set_format
snd_pcm_prepare
snd_pcm_writei
snd_pcm_drain
snd_pcm_close
https://www.alsa-project.org/alsa-doc/alsa-lib/group___p_c_m.html

issues

If your device can't support mixer feature, or pcm interface can't open multi times.
You can try PulseAudio.
pulseaudio example

compile cmd

gcc -o play play.c `pkg-config --cflags --libs alsa`

source

#include <alsa/asoundlib.h>
#include <stdio.h>

#define PCM_DEVICE "default"

int main(int argc, char** argv) {
  unsigned int pcm, tmp, dir;
  int rate, channels, seconds;
  snd_pcm_t* pcm_handle;
  snd_pcm_hw_params_t* params;
  snd_pcm_uframes_t frames;
  char* buff;
  int buff_size, loops;

  if (argc < 4) {
    printf("Usage: %s <sample_rate> <channels> <seconds>\n", argv[0]);
    return -1;
  }

  rate = atoi(argv[1]);
  channels = atoi(argv[2]);
  seconds = atoi(argv[3]);

  /* Open the PCM device in playback mode */
  if (pcm =
          snd_pcm_open(&pcm_handle, PCM_DEVICE, SND_PCM_STREAM_PLAYBACK, 0) < 0)
    printf("ERROR: Can't open \"%s\" PCM device. %s\n", PCM_DEVICE,
           snd_strerror(pcm));

  /* Allocate parameters object and fill it with default values*/
  snd_pcm_hw_params_alloca(&params);

  snd_pcm_hw_params_any(pcm_handle, params);

  /* Set parameters */
  if (pcm = snd_pcm_hw_params_set_access(pcm_handle, params,
                                         SND_PCM_ACCESS_RW_INTERLEAVED) < 0)
    printf("ERROR: Can't set interleaved mode. %s\n", snd_strerror(pcm));

  if (pcm = snd_pcm_hw_params_set_format(pcm_handle, params,
                                         SND_PCM_FORMAT_S16_LE) < 0)
    printf("ERROR: Can't set format. %s\n", snd_strerror(pcm));

  if (pcm = snd_pcm_hw_params_set_channels(pcm_handle, params, channels) < 0)
    printf("ERROR: Can't set channels number. %s\n", snd_strerror(pcm));

  if (pcm = snd_pcm_hw_params_set_rate_near(pcm_handle, params, &rate, 0) < 0)
    printf("ERROR: Can't set rate. %s\n", snd_strerror(pcm));

  /* Write parameters */
  if (pcm = snd_pcm_hw_params(pcm_handle, params) < 0)
    printf("ERROR: Can't set harware parameters. %s\n", snd_strerror(pcm));

  /* Resume information */
  printf("PCM name: '%s'\n", snd_pcm_name(pcm_handle));

  printf("PCM state: %s\n", snd_pcm_state_name(snd_pcm_state(pcm_handle)));

  snd_pcm_hw_params_get_channels(params, &tmp);
  printf("channels: %i ", tmp);

  if (tmp == 1)
    printf("(mono)\n");
  else if (tmp == 2)
    printf("(stereo)\n");

  snd_pcm_hw_params_get_rate(params, &tmp, 0);
  printf("rate: %d bps\n", tmp);

  printf("seconds: %d\n", seconds);

  /* Allocate buffer to hold single period */
  snd_pcm_hw_params_get_period_size(params, &frames, 0);

  buff_size = frames * channels * 2 /* 2 -> sample size */;
  buff = (char*)malloc(buff_size);

  snd_pcm_hw_params_get_period_time(params, &tmp, NULL);

  for (loops = (seconds * 1000000) / tmp; loops > 0; loops--) {
    if (pcm = read(0, buff, buff_size) == 0) {
      printf("Early end of file.\n");
      return 0;
    }

    printf("write data\n");
    if (pcm = snd_pcm_writei(pcm_handle, buff, frames) == -EPIPE) {
      printf("XRUN.\n");
      snd_pcm_prepare(pcm_handle);
    } else if (pcm < 0) {
      printf("ERROR. Can't write to PCM device. %s\n", snd_strerror(pcm));
    }
  }

  snd_pcm_drain(pcm_handle);
  snd_pcm_close(pcm_handle);
  free(buff);

  return 0;
}

fix autoconf error : possibly undefined macro: AC_SEARCH_LIBS

configure.ac:109: error: possibly undefined macro: AC_SEARCH_LIBS
If this token and others are legitimate, please use m4_pattern_allow.
See the Autoconf documentation.
autoreconf: /usr/local/bin/autoconf failed with exit status: 1
autoreconf failed

solution

sudo apt install libtool

notes, all below should be installed

autoconf automake m4 libtool libevent perl pkg-config 

How to install nvidia drivers on ubuntu

First update your new system

sudo apt-get update 
sudo apt-get dist-upgrade 

ensure what graphics driver your system needs.

ubuntu-drivers devices 

install intel driver first

sudo apt-get install intel-microcode 
sudo apt-get install nvidia-xxx 
That's all.

Note: nvidia-xxx

you must enter the recommended driver version displayed in ubuntu-drivers devices and I must warn you. Updating the kernel may cause you problems, so once you installed that NVIDIA driver, please don't upgrade with this commands (sudo apt dist-upgrade or sudo apt upgrade and sudo apt-get dist-upgrade), please use sudo apt-get upgrade that command will hold new kernel releases.

fixed: embedded-redis: Unable to run on macOS Sonoma

Issue you might see below error while trying to run embedded-redis for your testing on your macOS after you upgrade to Sonoma. java.la...