首页 > 编程语言 >[Node.js] Fetch csv data and parse

[Node.js] Fetch csv data and parse

时间:2023-02-05 01:44:18浏览次数:59  
标签:Node parser needle js parse records file csv

We use needleas a client on Node.js express server for fetching the data or site. https://www.npmjs.com/package/needle

The leanest and most handsome HTTP client in the Nodelands.

var needle = require('needle');

needle.get('http://www.google.com', function(error, response) {
  if (!error && response.statusCode == 200)
    console.log(response.body);
});
Callbacks not floating your boat? Needle got your back.

var data = {
  file: '/home/johnlennon/walrus.png',
  content_type: 'image/png'
};

// the callback is optional, and needle returns a `readableStream` object
// that triggers a 'done' event when the request/response process is complete.
needle
  .post('https://my.server.com/foo', data, { multipart: true })
  .on('readable', function() { /* eat your chunks */ })
  .on('done', function(err) {
    console.log('Ready-o!');
  })

 

Then we use csv-parse to parse the content: https://www.npmjs.com/package/csv-parse

import assert from 'assert';
import { parse } from 'csv-parse';

const records = [];
// Initialize the parser
const parser = parse({
  delimiter: ':'
});
// Use the readable stream api to consume records
parser.on('readable', function(){
  let record;
  while ((record = parser.read()) !== null) {
    records.push(record);
  }
});
// Catch any error
parser.on('error', function(err){
  console.error(err.message);
});
// Test that the parsed records matched the expected records
parser.on('end', function(){
  assert.deepStrictEqual(
    records,
    [
      [ 'root','x','0','0','root','/root','/bin/bash' ],
      [ 'someone','x','1022','1022','','/home/someone','/bin/bash' ]
    ]
  );
});
// Write data to the stream
parser.write("root:x:0:0:root:/root:/bin/bash\n");
parser.write("someone:x:1022:1022::/home/someone:/bin/bash\n");
// Close the readable stream
parser.end();

 

---- 

In this example, the pipe function is used to stream the data from the remote CSV file to a local file, and the on method is used to listen for the done event, which is emitted once the file has finished downloading. The contents of the local file are then read using fs.readFileSync and parsed using csv-parse.

const needle = require('needle');
const parse = require('csv-parse');
const fs = require('fs');

needle.get('https://example.com/file.csv')
  .pipe(fs.createWriteStream('file.csv'))
  .on('done', function() {
    // read the file once it's finished downloading
    const csv = fs.readFileSync('file.csv', 'utf-8');
    // parse the CSV content
    const records = parse(csv, {
      columns: true,
      trim: true
    });
    // do something with the parsed data
    console.log(records);
  });

 

标签:Node,parser,needle,js,parse,records,file,csv
From: https://www.cnblogs.com/Answer1215/p/17092757.html

相关文章

  • [Node.js] Migration with Umzug
    https://www.npmjs.com/package/umzug//index.jsconst{Sequelize}=require('sequelize');const{Umzug,SequelizeStorage}=require('umzug');constsequel......
  • vue.js客服系统实时聊天项目开发(二十二)vue项目中router.js路由介绍
    vue项目的路由就相当于我们在网址url上输入的地址,访问的具体网址就是路由拿到项目先看看路由文件,就能知道具体的访问地址了例如下面的router.jsimportVuefrom'vue'......
  • vue系列之模拟数据(mockjs)
    开发时,后端还没完成数据输出,前端只好写静态模拟数据。数据牵制与后端,前端页面无法很好的展示,效果不好展示,尤其是使用vue的v-for 或者react循环数据的时候,各种......
  • vuejs从入门到精通——watch侦听器——侦听数据源类型
    watch侦听器——侦听数据源类型https://cn.vuejs.org/guide/essentials/watchers.html#basic-examplewatch的第一个参数可以是不同形式的“数据源”:它可以是一个ref(包......
  • js画布封装之平铺(排版)
     实现代码:1import{UTILS}from"./Utils.js";2import{CanvasImageDraw,CanvasEvent,CanvasImageScroll,CanvasImageCustom}from"./ElementUtils.js";......
  • vuejs从入门到精通——watch侦听器
    watch侦听器https://cn.vuejs.org/guide/essentials/watchers.html虽然计算属性在大多数情况下更适合,但有时也需要一个自定义的侦听器。 这就是为什么vue通过watch......
  • vuejs从入门到精通——计算属性缓存 vs 方法
    计算属性缓存vs方法https://cn.vuejs.org/guide/essentials/computed.html#basic-exampletemplate:<p>{{calculateBooksMessage()}}</p>js://组件中fun......
  • vuejs从入门到精通——可写计算属性
    可写计算属性https://cn.vuejs.org/guide/essentials/computed.html#basic-example 计算属性默认是只读的。当你尝试修改一个计算属性时,你会收到一个运行时警告。只在......
  • nodejs---执行任意js文件
    nodejs---执行任意js文件keywords:直接运行javascripttypescriptjstshello.jsconsole.log('HelloWorld!')命令行执行:nodehello.jstypescript文件(比如hello.......
  • Cesium 加载GeoJson数据,看不到实体效果
    问题我真的不知道为什么几乎每次要用Cesium加什么东西,不管是点线面还是图层,总是不顺利要加载一个GeoJson数据,数据包含几个点,需要展示点的位置和标签名称。用以下代码,打印......